Last active
April 30, 2017 23:31
-
-
Save robinhouston/868295ee48e13f806e44cee47e5970f2 to your computer and use it in GitHub Desktop.
Matt Day’s in-place permutation algorithm using JavaScript generators
This file contains 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
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