Skip to content

Instantly share code, notes, and snippets.

@myndzi
Last active October 18, 2015 17:25
Show Gist options
  • Save myndzi/9e18a54223236ae20539 to your computer and use it in GitHub Desktop.
Save myndzi/9e18a54223236ae20539 to your computer and use it in GitHub Desktop.
"use strict";
function bagGenerator(pieces, exclusions) {
var buf = pieces.slice(),
size = pieces.length,
ptr = -1;
var shuffle = function () {
for (var t, j, i = 1; i < size; i++) {
j = Math.random() * (i+1) |0;
t = buf[i];
buf[i] = buf[j];
buf[j] = t;
}
ptr = size;
};
shuffle();
// as written, this will yield an infinite loop if all pieces
// in the 'pieces' array are also members of the 'exclusions' array
while (exclusions.indexOf(buf[size - 1]) > -1) {
buf.unshift(buf.pop());
}
return function () {
var ret = buf[--ptr];
if (!ptr) shuffle();
return ret;
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment