| 1 | (* Map's remove and next, against an array that holds the same: keys |
| 2 | hashed into runs of eight, so that removing moves entries back, |
| 3 | around the end of the slots too. *) |
| 4 | module MapRemove; |
| 5 | import Fmt, Heap, Rt, Ints := Map(I64, I64, near, same); |
| 6 | |
| 7 | const N = 500; |
| 8 | |
| 9 | proc near(k: I64): U64; |
| 10 | begin |
| 11 | return U64(k div 8 * 977); |
| 12 | end; |
| 13 | |
| 14 | proc same(a, b: I64): BOOL; |
| 15 | begin |
| 16 | return a = b; |
| 17 | end; |
| 18 | |
| 19 | proc main*; |
| 20 | var |
| 21 | m: Ints.Map; want: [N]I64; i: INT; k, v, n, sum, seed: I64; |
| 22 | found, _ok: BOOL; |
| 23 | begin |
| 24 | Ints.init(m, Heap.heap); |
| 25 | seed := 1; |
| 26 | for i := 1 to 20000 do |
| 27 | seed := (seed * 1103515245 + 12345) & 7FFFFFFFH; |
| 28 | k := seed mod N; |
| 29 | if seed div N mod 3 = 0 then |
| 30 | if Ints.remove(m, k) # (want[k] # 0) then Rt.stop("remove: wrong answer"); end; |
| 31 | want[k] := 0; |
| 32 | else |
| 33 | _ok := Ints.put(m, k, i); |
| 34 | want[k] := i; |
| 35 | end; |
| 36 | end; |
| 37 | for k := 0 to N - 1 do |
| 38 | v, found := Ints.get(m, k); |
| 39 | if (found # (want[k] # 0)) or (v # want[k]) then Rt.stop("get: not what was put"); end; |
| 40 | if found then INC(n); INC(sum, v); end; |
| 41 | end; |
| 42 | if Ints.remove(m, N) then Rt.stop("remove: a key never put"); end; |
| 43 | Fmt.print("{} entries, {} of them, summing {}\n", [Fmt.int(m.len), Fmt.int(n), Fmt.int(sum)]); |
| 44 | (* the walk sees each entry once *) |
| 45 | n := 0; sum := 0; |
| 46 | i, k, v := Ints.next(m, 0); |
| 47 | while i >= 0 do |
| 48 | if want[k] # v then Rt.stop("next: not what was put"); end; |
| 49 | want[k] := 0; |
| 50 | INC(n); INC(sum, v); |
| 51 | i, k, v := Ints.next(m, i); |
| 52 | end; |
| 53 | Fmt.print("walked {}, summing {}\n", [Fmt.int(n), Fmt.int(sum)]); |
| 54 | end; |
| 55 | |
| 56 | end MapRemove. |