Skip to content

Instantly share code, notes, and snippets.

@builtinnya
Created March 12, 2013 15:31
Show Gist options
  • Save builtinnya/5143894 to your computer and use it in GitHub Desktop.
Save builtinnya/5143894 to your computer and use it in GitHub Desktop.
A straightforward way to calculate permutations.
function permutations(arr) {
var result = [];
function remove(arr, index) {
return arr.filter(function(_, i) {
return index !== i;
});
}
function rec(arr, acc) {
result.push(acc);
arr.forEach(function(item, index) {
rec(remove(arr, index), acc.concat(item));
});
}
rec(arr, []);
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment