Last active
December 30, 2015 05:09
-
-
Save liquorice/7780438 to your computer and use it in GitHub Desktop.
Unrandom — for when someone says they want a random selection, but what they mean is uniformly sampled without repetition.
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
// Usage: | |
// var randomiser = new Unrandom(["alpha", "bravo", "charlie", "delta"]); | |
// console.debug(randomiser.get()); | |
var Unrandom = function(_items) { | |
var items, | |
last_item, | |
marker = 0; | |
var init = function() { | |
items = _items; | |
shuffle(); | |
}; | |
var get = function() { | |
var new_item = last_item; | |
while (new_item == last_item) { | |
marker += 1; | |
if (marker == items.length) { | |
shuffle(); | |
marker = 0; | |
} | |
new_item = items[marker]; | |
} | |
last_item = new_item; | |
return new_item; | |
}; | |
var shuffle = function() { | |
var l = items.length, t, r; | |
if (l == 0) return; | |
while (--l) { | |
r = Math.floor(Math.random() * l + 1); | |
t = items[l]; | |
items[l] = items[r]; | |
items[r] = t; | |
} | |
} | |
init(); | |
return { | |
get: get | |
}; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment