All pages 5 of 8
The hash table
A coat check that works out each coat's hook from the coat itself, so you can go straight to it.
Counted: 3 steps
The steps
- act adds up to 1 + 3 + 20 = 24, and 24 shared by 8 leaves 0: bucket 0.
- Bucket 0 holds cat first, not act, so look at the next word.
- The next word is act: that is it.
- Found act in 3 steps.
What it is
Picture a coat check with 8 hooks. Instead of a ticket, the clerk works out a hook number from your coat. When you come back, the clerk works it out again and goes straight to the right hook.
This is called a hash table. The rule that turns a thing into a number is called a hash. Each hook is called a bucket.
How a move works
Here the things are short words. Give each letter its place in the alphabet, so a is 1 and z is 26. Add them up and share the total by 8. What is left over is the bucket.
For cat, 3 and 1 and 20 make 24. Share 24 by 8 and nothing is left, so cat goes in bucket 0. Dog makes 26, which leaves 2, so dog goes in bucket 2.
Now put act. Its letters add up to 24 as well, so it lands in bucket 0, just behind cat. To get act back, work out the bucket, look at cat, then look at act. That is 3 steps.
Where you meet it
Hash tables are behind the names in your phone, the words in a spell checker and the logins on a website. Most coding languages have one built in, called a dictionary or a map.
Watch out for
Words made of the same letters, like cat and act, land in the same bucket here. That is because adding up ignores the order of the letters. When lots of words share a bucket, a find has to look through them all. A real hash mixes the order in, so the words spread out.