Skip to content

Instantly share code, notes, and snippets.

@MrAwesomeness
Created April 7, 2015 21:59
Show Gist options
  • Save MrAwesomeness/31fee1eb0dacc4efd25e to your computer and use it in GitHub Desktop.
Save MrAwesomeness/31fee1eb0dacc4efd25e to your computer and use it in GitHub Desktop.
Guess a number between 1 and 100 game written in JavaScript. The code is compatible to run at http://repl.it/ and it has a built in cheat function that uses a binary search to find the answer
console.log('Guess a number from 1 to 100 or type "Cheat" to find the answer');
var answer = Math.floor((Math.random() * 100) + 1);
var i = 1;
//var c = 1;
function guessNum(answer){
var min = 0;
var max = 100;
var mid;
while (mid != answer){
mid = Math.floor((max + min)/2);
//console.log(mid);
if(mid === answer){
//console.log(c);
console.log(mid);
}
else if (mid < answer){
min = mid;
}
else {
max = mid;
}
// c++;
}
}
while (guess != answer){
var guess = prompt();
if (guess > 100){
console.log("Error, Cannot be bigger than 100");
}
else if (guess < 0){
console.log("Error, Cannot be smaller than 0");
}
else if (guess == answer){
console.log("You are correct, the answer is " + answer);
console.log("It took you " + i +" tries");
}
else if (guess < answer){
console.log("too low");
}
else if (guess > answer){
console.log("too high");
}
else if (guess == "Cheat"){
guessNum(answer);
}
i++;
}
@aaradhy01
Copy link

nice work!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment