-
Notifications
You must be signed in to change notification settings - Fork 1
/
k_way_merging_test.go
179 lines (160 loc) · 3.11 KB
/
k_way_merging_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
package merging_k_sorted_list
import (
"bufio"
"container/heap"
"fmt"
"io"
"math/rand"
"os"
"sort"
"strconv"
"testing"
)
func createNSortedInDir(dir string) {
N := 10
for i := 0; i < N; i++ {
fileName := fmt.Sprintf("%04d.dat", i)
filePath := dir + "/" + fileName
file, err := os.Create(filePath)
if err != nil {
panic(err)
}
nums := make([]int, N, N)
for i := 0; i < N; i++ {
nums[i] = rand.Intn(100)
}
sort.Ints(nums)
for i := 0; i < N; i++ {
bytes := []byte(fmt.Sprintf("%d", nums[i]))
_, _ = file.Write(bytes)
if i != N-1 {
_, _ = file.Write([]byte("\n"))
}
}
}
}
// mkdirOrRemove creates a directory if it does not exist,
// or removes all files in the directory if it exists.
func mkdirOrRemove(dir string) {
if _, err := os.Stat(dir); os.IsNotExist(err) {
err := os.MkdirAll(dir, 0755)
if err != nil {
panic(err)
}
} else {
files, err := os.ReadDir(dir)
if err != nil {
panic(err)
}
for _, file := range files {
err = os.Remove(dir + "/" + file.Name())
if err != nil {
panic(err)
}
}
}
}
type Block struct {
r *bufio.Reader
isEof bool
line string
}
func NewBlock(path string) Block {
file, err := os.Open(path)
if err != nil {
panic(err)
}
r := bufio.NewReader(file)
return Block{
r: r,
isEof: false,
}
}
type Iterator interface {
Next() bool
Value() int
}
func (b *Block) Next() bool {
line, _, err := b.r.ReadLine()
if err != nil {
if err != io.EOF {
panic("unexpected error")
}
return false
}
b.line = string(line)
return true
}
func (b *Block) Value() int {
n, err := strconv.Atoi(b.line)
if err != nil {
panic("should not happen")
}
return n
}
func listFilesInDir(dir string) []string {
files, err := os.ReadDir(dir)
if err != nil {
panic("open failed")
}
result := make([]string, 0)
for _, file := range files {
filePath := dir + "/" + file.Name()
result = append(result, filePath)
}
return result
}
func TestMerging(t *testing.T) {
dir := "/tmp/k_way_merging"
mkdirOrRemove(dir)
createNSortedInDir(dir)
files := listFilesInDir(dir)
iters := make([]Block, 0)
for _, file := range files {
iters = append(iters, NewBlock(file))
}
itersLen := len(iters)
pq := &MinHeap{}
heap.Init(pq)
for i := 0; i < itersLen; i++ {
if !iters[i].Next() {
continue
}
entry := Entry{
value: iters[i].Value(),
iterIdx: i,
}
heap.Push(pq, entry)
}
for pq.Len() > 0 {
item := heap.Pop(pq).(Entry)
println(item.value)
if iters[item.iterIdx].Next() {
newEntry := Entry{
value: iters[item.iterIdx].Value(),
iterIdx: item.iterIdx,
}
heap.Push(pq, newEntry)
}
}
}
// implement priority queue using min-heap
type Entry struct {
value int
iterIdx int
}
type MinHeap []Entry
func (h MinHeap) Len() int { return len(h) }
func (h MinHeap) Less(i, j int) bool { return h[i].value < h[j].value }
func (h MinHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] }
func (h *MinHeap) Push(x interface{}) {
*h = append(*h, x.(Entry))
}
func (h *MinHeap) Pop() interface{} {
old := *h
n := len(old)
x := old[n-1]
*h = old[0 : n-1]
return x
}
// end of min-heap