Created
August 6, 2023 13:45
-
-
Save 607011/a093226d74bd0ff70bb211500fad43f8 to your computer and use it in GitHub Desktop.
All permutations
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* allPermutations(arr) { | |
const c = new Array(arr.length).fill(0); | |
let i = 1; | |
while (i < arr.length) { | |
if (c[i] < i) { | |
yield [...arr]; | |
const k = i % 2 && c[i]; | |
[arr[i], arr[k]] = [arr[k], arr[i]]; | |
++c[i]; | |
i = 1; | |
} | |
else { | |
c[i] = 0; | |
++i; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment