Skip to content

Instantly share code, notes, and snippets.

@bobwei
Created November 29, 2018 14:30
Show Gist options
  • Save bobwei/ed3144fa5288c2b96a3fda29f9e5c840 to your computer and use it in GitHub Desktop.
Save bobwei/ed3144fa5288c2b96a3fda29f9e5c840 to your computer and use it in GitHub Desktop.
permutation.js
const createPermutation = (arr, selected = new Set(), output = []) => {
if (selected.size >= arr.length) {
output.push([...selected].map((i) => arr[i]));
return output;
}
for (let i = 0; i < arr.length; i++) {
if (selected.has(i)) {
continue;
}
selected.add(i);
createPermutation(arr, selected, output);
selected.delete(i);
}
return output;
};
const result = createPermutation([1, 2, 3]);
console.log(result);
/*
[
[ 1, 2, 3 ],
[ 1, 3, 2 ],
[ 2, 1, 3 ],
[ 2, 3, 1 ],
[ 3, 1, 2 ],
[ 3, 2, 1 ]
]
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment