Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript JavaScript Loops, Arrays and Objects Simplify Repetitive Tasks with Loops `do ... while` Loops

Michal Bosnovic
Michal Bosnovic
996 Points

How to stop computer guessing the same number more than once?

I was just wondering, how to make the computer not guess the same numbers if they are not correct.

1 Answer

Bryan Peters
Bryan Peters
11,996 Points

You could store the previous guesses in an array, and pull a new random number if the current number has already been used.

You would also need to check if the length of the array matches the range so that you don't get into an infinite loop - If you are generating a number between 1 and 6, and your previousGuesses array has 6 unique entries, there are no more unique numbers left to guess, so you would need to stop computer from guessing.

EDIT: it would be more efficient to have an array of all possible values, and splice out a value from a random position between 0 and the length of the array. The array length would get shorter for each guess, and you would always be guaranteed a unique guess.

Your edit is definitely the better way to go. Your first suggestion isn't all that different from what's currently happening. The computer is still making duplicate guesses.

Also I don't think your infinite loop situation is possible unless the secret number is outside the range. The computer will eventually guess the correct number.