Skip to content

Instantly share code, notes, and snippets.

@607011
Created August 6, 2023 13:45
Show Gist options
  • Save 607011/a093226d74bd0ff70bb211500fad43f8 to your computer and use it in GitHub Desktop.
Save 607011/a093226d74bd0ff70bb211500fad43f8 to your computer and use it in GitHub Desktop.
All permutations
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