I am writing a program for fun and practice that takes a user input and guesses the input value. I can't take a prompt however in my testing environment, so I use the number 5 instead, and I also use debug instead of console.log. I cannot find the location of where the infinite loop starts, as far as I can tell it just counts up an array until it gets to the string '5', and the loop should be stopped. I need a second pair of eyes on this one, Stack Overflow. Thanks!
//Password Cracker
//"userPassword" will not be read by the computer, instead it will be guessed and reguessed.
var userPassword = 5 + ''
//the following variable contains an array of all the possible characters that can be present.
var possibleCharacters = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','1','2','3','4','5','6','7','8','9','0'];
//the computer's current guess.
var computerGuess = null;
//establishes that the computer has not correctly guessed the password, will be changed when password is discovered.
var correctGuess = null;
//the following variable keeps track of how many guesses it takes for the computer to crack the password.
var totalGuesses = 0;
//the following function checks if the current guess of the computer matches the password inputted by the user.
var checkPassword = function(passwordGuess) {
if(passwordGuess === userPassword) {
debug("Your password is " + computerGuess + ". Gotta do better to fool me!");
}else{
debug("Guessing again.");
};
};
//the loop that should stop when the password has been guessed correctly. the variable 'i' counts up through the strings in the array.
while(computerGuess !== userPassword) {
for(var i = 0; i < 61; i++) {
computerGuess = possibleCharacters[i];
checkPassword(computerGuess);
};
};
end;
//the loop that should stop when the password has been guessed correctly. the variable 'i' counts up through the strings in the array.
while(computerGuess !== userPassword) {
for(var i = 0; i < 61; i++) {
computerGuess = possibleCharacters[i];
checkPassword(computerGuess);
};
};
This is an infinite loop since the inner loop (the for
loop) always iterates through all characters, so computerGuess is '0'
at the end. Therefore, the while condition is always satisfied. You could solve that by breaking the for loop once you have guessed the right password:
while(computerGuess !== userPassword) {
for(var i = 0; i < 61 && computerGuess !== userPassword; i++) {
computerGuess = possibleCharacters[i];
checkPassword(computerGuess);
};
};