Skip to content

Instantly share code, notes, and snippets.

@zerobias
Created October 26, 2018 10:01
Show Gist options
  • Save zerobias/6116d2807aa496dc242469eef0860741 to your computer and use it in GitHub Desktop.
Save zerobias/6116d2807aa496dc242469eef0860741 to your computer and use it in GitHub Desktop.
const generatePermutations = (items, process) => {
const mutableItems = items.slice();
const isEven = n => (n & 1) === 0;
const permute = (itemArray, x, last) => {
if (isEven(last)) { x = 0; }
const temp = itemArray[x];
itemArray[x] = itemArray[last];
itemArray[last] = temp;
};
const generate = function generateNext(last, process) {
let i;
if (last === 0) {
process(mutableItems);
}
else {
for (i = 0; i < last; i += 1) {
generateNext(last - 1, process);
permute(mutableItems, i, last);
}
generateNext(last - 1, process);
}
};
generate(mutableItems.length - 1, process);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment