Created
April 7, 2015 21:59
-
-
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
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
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++; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
nice work!