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 trialMichal Bosnovic
996 PointsHow 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
11,996 PointsYou 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.
Jason Anello
Courses Plus Student 94,610 PointsJason Anello
Courses Plus Student 94,610 PointsYour 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.