Skip to content

Instantly share code, notes, and snippets.

@claytonjwong
Created November 20, 2021 16:34
Show Gist options
  • Save claytonjwong/1176f11758cf157caa54c9b1f2d750b2 to your computer and use it in GitHub Desktop.
Save claytonjwong/1176f11758cf157caa54c9b1f2d750b2 to your computer and use it in GitHub Desktop.
Returns the permutations of the array A
let permutations = A => {
let N = A.length;
let perms = [];
let go = (i = 0) => {
if (i == N) {
perms.push([...A]);
return;
}
for (let k = i; k < N; ++k) {
[A[i], A[k]] = [A[k], A[i]];
go(i + 1);
[A[i], A[k]] = [A[k], A[i]];
}
};
go();
return perms;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment