76
Chapter 5
I
Hash tables
Hash functions
A hash function is a function where you put in a string
1
and you get
back a number.
In technical terminology, we’d say that a hash function “maps strings
to numbers.” You might think there’s no discernable pattern to what
number you get out when you put a string in. But there are some
requirements for a hash function:
• It needs to be consistent. For example, suppose you put in “apple” and
get back “4”. Every time you put in “apple”, you should get “4” back.
Without this, your hash table won’t work.
• It should map different words to different numbers. For example, a
hash function is no good if it always returns “1” for any word you put
in. In the best case, every different word should map to a different
number.
So a hash function maps strings to numbers. What is that good for?
Well, you can use it to make your “Maggie”!
Start with an empty array:
You’ll store all of your prices in this array. Let’s add the price of an apple.
Feed “apple” into the hash function.
Dostları ilə paylaş: