Last active
December 8, 2015 17:11
-
-
Save toddbranch/e9169ccaf7498006bc5d to your computer and use it in GitHub Desktop.
randomFromStream
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
function randomFromStream() { | |
var length = 0; | |
var result = null; | |
var potentialResult; | |
while(potentialResult = gfs()) { | |
length += 1; | |
if (Math.floor(Math.random() * length) === 0) { | |
result = potentialResult; | |
} | |
} | |
return result; | |
} | |
var result = randomFromStream(); |
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
function randomFromStream(currentResult, length) { | |
var potentialResult = gfs(); | |
// no more numbers in stream | |
if (potentialResult === null) { | |
return currentResult; | |
} | |
length += 1; | |
if (Math.floor(Math.random() * length) === 0) { | |
currentResult = potentialResult; | |
} | |
return randomFromStream(currentResult, length); | |
} | |
var result = randomFromStream(null, 0); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment