-
-
Save IrhaAli/3e99bf21aa2d604e8a8ffb17cf835e61 to your computer and use it in GitHub Desktop.
Prompts the user to guess the number the computer generated
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//set up before the main algorithm | |
let prompt = require("prompt-sync")(); | |
//in the case that the answer is not a number. | |
const isNumber = function() { | |
while (Number(answer) === NaN){ | |
console.log('Not a number! Try again!'); | |
answer = prompt("Guess a number: "); | |
} | |
} | |
//generate a random number between 1 to 1000 | |
let solution = Math.ceil(Math.random()*1000); | |
//get the first answer from the user | |
let answer = prompt("Guess a number: "); | |
//to track all attempts | |
let solutionTracker = []; | |
//ensures the input is a number, before entering the while loop | |
isNumber(); | |
while ((answer !== solution)){ | |
if (solutionTracker.includes(answer)){ | |
console.log('Already Guessed!'); | |
}else if (answer < solution){ | |
console.log('Too low'); | |
}else if (answer > solution){ | |
console.log('too high'); | |
} | |
solutionTracker.push(answer); | |
if (answer == solution){ | |
let attempts = [...new Set(solutionTracker)].length; | |
if (attempts === 1){ | |
console.log(`You got it! You took ${attempts} attempt!`); | |
}else { | |
console.log(`You got it! You took ${[...new Set(solutionTracker)].length} attempts!`); | |
} | |
break; | |
} | |
//asks for another guess for the next iteration | |
answer = prompt("Guess a number: "); | |
//ensures the input is a number before re-rentering the while loop | |
isNumber(); | |
} | |
//personal comment: I don't really like my solution that much. I feel like using in-built methods might make the algorithm less efficient. I would love some feedback. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment