A Guessing Game PDF
A Guessing Game PDF
Let's play a little game to give you an idea of how different algorithms for
the same problem can have wildly different efficiencies. The computer is
going to randomly select an integer from 1 to 16. You'll keep guessing
numbers until you find the computer's number, and the computer will
tell you each time if your guess was too high or too low:
https://mybinder.org/v2/gh/emefer/Guessing-Game.git/master?filepath=guessing_game_1_10.ipynb
Once you've found the number, reflect on what technique you used when
deciding what number to guess next.
Maybe you guessed 1, then 2, then 3, then 4, and so on, until you guessed
the right number. We call this approach linear search, because you
guess all the numbers as if they were lined up in a row. It would work.
But what is the highest number of guesses you could need? If the
computer selects 16, you would need 16 guesses. Then again, you could
be really lucky, which would be when the computer selects 1 and you get
the number on your first guess. How about on average? If the computer
is equally likely to select any number from 1 to 16, then on average you'll
need 8 guesses.
Here, try it for a number from 1 to 300. You should need no more than 9
guesses.
https://mybinder.org/v2/gh/emefer/Guessing-Game.git/master?filepath=guessing_game_1_300.ipynb
How many guesses did it take you to find the number this time? Why
should you never need more than 9 guesses? (Can you think of a
mathematical explanation)?
We'll return to binary search, and we'll see how you can use it to
efficiently search for an item in a JavaScript array. But first, let's look at
an algorithm for a trickier problem.