| 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 | fn test_min_heap_insert_many() { |
| 22 | mut heap := MinHeap[int]{} |
| 23 | elem := [2, 0, 8, 4, 1] |
| 24 | heap.insert_many(elem) |
| 25 | |
| 26 | assert heap.pop()! == 0 |
| 27 | assert heap.peek()! == 1 |
| 28 | heap.pop()! |
| 29 | assert heap.peek()! == 2 |
| 30 | } |
| 31 | |
| 32 | struct Item { |
| 33 | data string |
| 34 | priority int |
| 35 | } |
| 36 | |
| 37 | fn (lhs Item) < (rhs Item) bool { |
| 38 | return rhs.priority < lhs.priority |
| 39 | } |
| 40 | |
| 41 | fn test_min_heap_custom() { |
| 42 | mut heap := MinHeap[Item]{} |
| 43 | heap.insert(Item{'buz', 10}) |
| 44 | heap.insert(Item{'qux', 0}) |
| 45 | heap.insert(Item{'baz', 50}) |
| 46 | heap.insert(Item{'foo', 100}) |
| 47 | heap.insert(Item{'bar', 80}) |
| 48 | |
| 49 | assert heap.pop()!.data == 'foo' |
| 50 | assert heap.pop()!.data == 'bar' |
| 51 | assert heap.pop()!.data == 'baz' |
| 52 | assert heap.pop()!.data == 'buz' |
| 53 | assert heap.pop()!.data == 'qux' |
| 54 | if _ := heap.pop() { |
| 55 | panic('expected none') |
| 56 | } |
| 57 | } |
| 58 | |
| 59 | fn test_heap_len() { |
| 60 | mut heap := MinHeap[int]{} |
| 61 | heap.insert(2) |
| 62 | assert heap.len() == 1 |
| 63 | heap.insert(0) |
| 64 | heap.insert(8) |
| 65 | heap.insert(4) |
| 66 | assert heap.len() == 4 |
| 67 | heap.insert(1) |
| 68 | |
| 69 | assert heap.len() == 5 |
| 70 | heap.pop()! |
| 71 | heap.pop()! |
| 72 | heap.pop()! |
| 73 | assert heap.len() == 2 |
| 74 | heap.pop()! |
| 75 | heap.pop()! |
| 76 | assert heap.len() == 0 |
| 77 | heap.pop() or {} |
| 78 | assert heap.len() == 0 |
| 79 | } |
| 80 | |