Skip to content

Instantly share code, notes, and snippets.

@apainintheneck
Created May 11, 2022 23:21
Show Gist options
  • Save apainintheneck/c297ce2743f8c752ac994b493cb1e7d8 to your computer and use it in GitHub Desktop.
Save apainintheneck/c297ce2743f8c752ac994b493cb1e7d8 to your computer and use it in GitHub Desktop.
A stock implementation of Heap's algorithm as a JS generator.
export function* permutations(array) {
let mutArray = array.slice();
if(mutArray.length > 0) yield mutArray.slice();
const stack = Array(mutArray.length).fill(0);
for(let i = 0; i < mutArray.length;) {
if(stack[i] < i) {
if(i % 2 === 0) {
[mutArray[0], mutArray[i]] = [mutArray[i], mutArray[0]];
} else {
[mutArray[stack[i]], mutArray[i]] = [mutArray[i], mutArray[stack[i]]];
}
yield mutArray.slice();
stack[i]++;
i = 0;
} else {
stack[i] = 0;
i++;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment