1 | module datatypes |
2 | |
3 | fn test_min_heap() { |
4 | mut heap := MinHeap[int]{} |
5 | heap.insert(2) |
6 | heap.insert(0) |
7 | heap.insert(8) |
8 | heap.insert(4) |
9 | heap.insert(1) |
10 | |
11 | assert heap.pop()! == 0 |
12 | assert heap.pop()! == 1 |
13 | assert heap.pop()! == 2 |
14 | assert heap.pop()! == 4 |
15 | assert heap.pop()! == 8 |
16 | if _ := heap.pop() { |
17 | panic('expected none') |
18 | } |
19 | } |
20 | |
21 | struct Item { |
22 | data string |
23 | priority int |
24 | } |
25 | |
26 | fn (lhs Item) < (rhs Item) bool { |
27 | return rhs.priority < lhs.priority |
28 | } |
29 | |
30 | fn test_min_heap_custom() { |
31 | mut heap := MinHeap[Item]{} |
32 | heap.insert(Item{'buz', 10}) |
33 | heap.insert(Item{'qux', 0}) |
34 | heap.insert(Item{'baz', 50}) |
35 | heap.insert(Item{'foo', 100}) |
36 | heap.insert(Item{'bar', 80}) |
37 | |
38 | assert heap.pop()!.data == 'foo' |
39 | assert heap.pop()!.data == 'bar' |
40 | assert heap.pop()!.data == 'baz' |
41 | assert heap.pop()!.data == 'buz' |
42 | assert heap.pop()!.data == 'qux' |
43 | if _ := heap.pop() { |
44 | panic('expected none') |
45 | } |
46 | } |
47 | |
48 | fn test_heap_len() { |
49 | mut heap := MinHeap[int]{} |
50 | heap.insert(2) |
51 | assert heap.len() == 1 |
52 | heap.insert(0) |
53 | heap.insert(8) |
54 | heap.insert(4) |
55 | assert heap.len() == 4 |
56 | heap.insert(1) |
57 | |
58 | assert heap.len() == 5 |
59 | heap.pop()! |
60 | heap.pop()! |
61 | heap.pop()! |
62 | assert heap.len() == 2 |
63 | heap.pop()! |
64 | heap.pop()! |
65 | assert heap.len() == 0 |
66 | heap.pop() or {} |
67 | assert heap.len() == 0 |
68 | } |