Created
May 11, 2022 23:21
-
-
Save apainintheneck/c297ce2743f8c752ac994b493cb1e7d8 to your computer and use it in GitHub Desktop.
A stock implementation of Heap's algorithm as a JS generator.
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
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