Last active
August 29, 2015 14:25
-
-
Save programmarchy/5d24f48c28bea83ef8eb to your computer and use it in GitHub Desktop.
choices choices choices
This file contains hidden or 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 choices(n) { | |
var map = {} | |
var rand = function (n) { | |
return Math.floor(n * Math.random()) | |
} | |
var stride = (n / 2) | |
var i = rand(n) | |
var max = 0 | |
this.choose = function() { | |
if (max === n) { | |
return -1 | |
} else { | |
var x = i | |
while (map[x]) { | |
i = (i + rand(stride)) % n | |
x = i | |
} | |
map[x] = true | |
max++ | |
return x | |
} | |
} | |
return this | |
} | |
var c = choices(10) | |
console.log(c.choose()) | |
console.log(c.choose()) | |
console.log(c.choose()) | |
console.log(c.choose()) | |
console.log(c.choose()) | |
console.log(c.choose()) | |
console.log(c.choose()) | |
console.log(c.choose()) | |
console.log(c.choose()) | |
console.log(c.choose()) | |
console.log(c.choose()) | |
console.log(c.choose()) | |
/** | |
> node choose | |
2 | |
6 | |
8 | |
4 | |
5 | |
9 | |
0 | |
3 | |
7 | |
1 | |
-1 | |
-1 | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment