Code

Growing, statistics, keys — write them yourself

Put works. The remaining three parts — growing, chain statistics and the key list — come without holes this time: empty skeletons, and you fill them in completely.

You have already seen growing in the second table of the last step. Below is the same table written as pseudocode.

Growing

When items multiply and buckets do not, the chains get longer and O(1) turns into a lie.

The load factor = items ÷ buckets. When it reaches 1.0, the bucket count is doubled and everything is worked out again:

grow():
    old ← buckets
    buckets ← new array, 2x as large
    Resizes ← Resizes + 1
    for each entry e in old (through all the chains):
        i ← hashKey(e.key) % len(buckets)       // the NEW size
        e.next ← buckets[i]
        buckets[i] ← e

grow recomputes hashKey % new size. The old bucket number is meaningless after the doubling — that was the third observation of the last step (Ulysses and Emma: 1 and 1, then 1 and 5). Moving a chain as a whole is not allowed: you would leave keys in buckets nobody looks in any more.

It is an O(n) operation. But it happens rarely — exactly like lesson 2's append, and for the same reason. Amortisation is the same idea here.

Put already calls grow. Compare it with the last step's Put: a few lines appeared between the loop and HOLE 2 that grow the table when it is full. You do not write them — but it is worth noticing where they sit:

  • Grow BEFORE inserting. If you grow after inserting, the load factor will briefly exceed the limit — the test will notice.
  • Only for a new key. A repeated key returns earlier, so it never grows the table by itself.
  • The bucket number is recomputed after growing — because the size changed.

NoGrow is only for demonstration (-nogrow): it lets you see what happens without growing.

ChainStats

ChainStats():
    longest ← 0, empty ← 0, total ← 0, nonEmpty ← 0
    for each bucket:
        l ← length of its chain
        if l = 0:  empty ← empty + 1, continue
        nonEmpty ← nonEmpty + 1
        total ← total + l
        longest ← max(longest, l)
    mean ← total / nonEmpty        // 0 if nonEmpty = 0

The mean is taken over non-empty buckets only. With the empty ones included it would just be the load factor and would tell you nothing new; without them it shows how long a chain you actually walk when the bucket holds anything at all. In the last step's second table: 6 keys in five non-empty buckets, mean 1.2, not 0.75.

Keys

Keys():
    for each bucket in order, for each e in its chain from the front:
        append e.key
    return the list

Do not sort. The order means nothing here, and step 9 explains why that matters.

Your job

hash.go (in the panel) has grown: three new skeletons, grow, ChainStats and Keys, each with panic("not implemented"), and Put has gained the growing lines.

Put still shows up in the panel with its holes — the panel shows the skeleton, not your file. In your copy they are already filled in; leave them that way.

Read the contracts, not just the signatures. The doc comments state everything the test will check.

hash_test.go has grown too. It now checks six things:

test what it demands
TestHashIndexStoresAndFinds finds everything stored, does not find what was not
TestDuplicateKeysReplaceRatherThanAccumulate an equal key replaces, does not accumulate
TestFixedTableReproducesTheLessonTrace the first table of step 2, no growing
TestGrowingTableReproducesTheLessonTrace the second table: 2 resizes, 8 buckets, 7 comparisons, chain statistics
TestResizeKeepsTheLoadFactorBounded load ≤ 1.0 and < 4 comparisons per lookup
TestKeysAreNotInAnyUsefulOrder Keys() is NOT sorted

The last one looks odd — a test that demands something is not sorted. But it guards the end of the lesson the same way the tests of lessons 7 and 8 guarded the defects shown there. If you ever change Keys() to return a sorted list, the test will tell you what you lost: the index's promise is not "I will return them in order", and relying on luck is not allowed.

Run the test

While grow is empty, the test blows up the first time the table fills up:

$ go test ./...
--- FAIL: TestHashIndexStoresAndFinds (0.00s)
panic: not implemented [recovered, repanicked]
...
algo.(*HashIndex).grow(...)
...
algo.(*HashIndex).Put(...)

That is not an error — it is a pointer to what to write first: grow, which Put called. Fill in grow and move on to the others.

When it does not pass

  • Get("00000"): ok=false and resizes / buckets / stored = 2 / 8 / 7, want 2 / 8 / 6 — you moved the chains over without rehashing the keys. The keys stayed in buckets nobody looks in, and the repeated Dune was no longer found, so it was stored again.
  • resizes / buckets / stored = 0 / 8 / 6, want 2 / 8 / 6 — the table grew but you did not increment Resizes.
  • longest / empty / mean = 2 / 3 / 0.8, want 2 / 3 / 1.2 — you divided the mean by all the buckets, not the non-empty ones.
  • Keys() came back sorted — you sorted the keys. The test demands the opposite: what the index cannot promise must not appear by accident.