Menu

What a Number-Guessing Game Teaches About Binary Search and Vue State
📰

What a Number-Guessing Game Teaches About Binary Search and Vue State

DEV Community: javascript·Joe Lin·5 days ago
#jzTt7dXc
#devtojavascript#devto#dev#value#guess
Reading 0:00
15s threshold

A higher-or-lower number game can give misleading hints or attempt counts if the secret and round state change at the wrong time. I'll use a small Vue implementation to show how to keep those updates consistent, then explain why midpoint guesses put a worst-case bound on the number of attempts.

The player chooses a range, submits a number, and gets a high, low, or correct result. There is no computer player performing binary search. The useful connection is that the feedback gives a human player exactly the information needed to shrink a search interval.

Pick One Secret for the Whole Round

The implementation offers upper bounds of 10, 50, 100, and 1,000, always starting at 1. The target generator is deliberately ordinary:

function randomTarget ( max ) { return Math . floor ( Math . random ( ) * max ) + 1 ; }

Enter fullscreen mode

Exit fullscreen mode

Multiplying a random value in the interval from zero up to, but not including, one produces a value below max .…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.