Skip to content

Instantly share code, notes, and snippets.

@programmarchy
Last active August 29, 2015 14:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save programmarchy/5d24f48c28bea83ef8eb to your computer and use it in GitHub Desktop.
Save programmarchy/5d24f48c28bea83ef8eb to your computer and use it in GitHub Desktop.
choices choices choices
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