Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Activity 31: The room is a hash table

Name:

Today the room is the hash table. There are eight buckets on the walls, numbered 0 to 7. Your key is your first name. Each round puts a hash function on the screen; work out your bucket and go stand in it.

Letter values, for every round:

ABCDEFGHIJKLM
12345678910111213
NOPQRSTUVWXYZ
14151617181920212223242526

Round 1: first letter (in lecture)

hash(name) = value of the first letter. Bucket = hash % 8.

BucketFirst letter
0H P X
1A I Q Y
2B J R Z
3C K S
4D L T
5E M U
6F N V
7G O W

My bucket: ______    Longest pile: ______    Empty buckets: ______

Round 2: length

hash(name) = number of letters. Bucket = hash % 8. (Eight letters is bucket 0, nine is bucket 1.)

My bucket: ______    Longest pile: ______    Empty buckets: ______

Two names, Alice and Alicia, differ by one letter. Where do they land? Which property from the hash function slide does this function lack?



Answer. Alice is in bucket 5 and Alicia in bucket 6, but so is every other five- and six-letter name. The missing property is avalanche: a small change should scramble the whole output, and here it moves the key one bucket over. Uniform fails too, since most names are four to seven letters long so buckets 1 to 3 are empty.

Round 3: design a better one

With the people from your Round 2 bucket, design a hash function for first names that:

  1. anyone can compute in their head in ten seconds
  2. uses more of the name than one letter
  3. spreads this room more evenly than Rounds 1 and 2

Our function:



My bucket under it: ______    If we ran it, longest pile: ______

Answer. Anything that mixes two or more letters helps: first letter plus last letter, the sum of every letter, first letter plus length. On this term's roster those get the longest pile down from 8-12 to 5-7, vs an ideal of about 4. T

Round 4: two questions

a. Pick a brand-new name that would land in the fullest bucket under your group's function. How long did that take you? Which property is missing, and how does Rust's default hasher defend against it?



Answer. Seconds. Every function in this room is easy to run backwards: pick the bucket, pick letters that add up to it. That's an adversary choosing keys to collide. Rust's default hasher, SipHash, mixes every byte of the key with a random secret chosen when the program starts, so nobody outside the program can predict which keys collide.

b. Would your function still be flat for the other section's names? What does that say about what a hash function has to be good at?



Answer. No way to know. You designed it against the names in this room, like a library that knows its collection. A hash table doesn't know its keys ahead of time, so the function has to spread out keys it has never seen. That's what uniform means.