Skip to content

Instantly share code, notes, and snippets.

@liquorice
Last active December 30, 2015 05:09
Show Gist options
  • Save liquorice/7780438 to your computer and use it in GitHub Desktop.
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.
// 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