Created
July 19, 2015 06:09
-
-
Save itsananderson/82cb5da421b84880236b to your computer and use it in GitHub Desktop.
Solution for the consecutive numbers problem
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
// It's a bit messy, but it seems to work | |
function player(name) { | |
this.name = name; | |
this.questionCount = 0; | |
this.number; | |
} | |
player.prototype.setOther = function(other, otherNumber) { | |
this.other = other; | |
this.otherNumber = otherNumber; | |
this.possibleNumbers = [otherNumber - 1, otherNumber + 1]; | |
} | |
player.prototype.knowsNumber = function() { | |
if (this.number) { | |
this.end(); | |
return true; | |
} | |
// If more questions have been asked than the other person's number, | |
// and they still don't know what they are, we're the higher number | |
if (this.questionCount >= this.otherNumber) { | |
this.number = this.possibleNumbers[1]; | |
setTimeout(function() { | |
this.other.knowsNumber(); | |
}.bind(this)); | |
this.end(); | |
return true; | |
} else { | |
this.questionCount++; | |
setTimeout(this.ask.bind(this)); | |
} | |
} | |
player.prototype.ask = function() { | |
if (this.other.knowsNumber()) { | |
// If they figured theirs out first, that means we're the lower number | |
this.number = this.possibleNumbers[0]; | |
} else { | |
this.questionCount++; | |
} | |
} | |
player.prototype.end = function() { | |
console.log(this.name, this.number); | |
} | |
var i = 0; | |
var skew = 1; | |
var inter = setInterval(function() { | |
skew = (skew+1)%2; | |
if (skew === 0) { | |
i++; | |
} | |
if (i >= 10) { | |
clearInterval(inter); | |
} | |
var player1 = new player("player1"); | |
var player2 = new player("player2"); | |
// Associate players | |
player1.setOther(player2, i+1-skew); | |
player2.setOther(player1, i+skew); | |
// Kick off the questions | |
console.log("--"); | |
console.log("Should be player1:" + (i+skew) + " player2:" + (i+1-skew)); | |
player1.ask(); | |
}, 100); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment