Skip to content

Instantly share code, notes, and snippets.

@robinhouston
Last active April 30, 2017 23:31
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 robinhouston/868295ee48e13f806e44cee47e5970f2 to your computer and use it in GitHub Desktop.
Save robinhouston/868295ee48e13f806e44cee47e5970f2 to your computer and use it in GitHub Desktop.
Matt Day’s in-place permutation algorithm using JavaScript generators
function* allPermutationsOf(array, level=0) {
array = array.slice(0);
const calling = (level === array.length-1);
let index = level;
do {
if (calling) yield array;
else yield *allPermutationsOf(array, level+1);
if (index > 0) {
const tmp = array[index];
array[index] = array[index-1];
array[index-1] = tmp;
}
} while (index-- > 0);
}
for (const a of allPermutationsOf([1,2,3])) console.log(a);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment