Skip to content

Instantly share code, notes, and snippets.

@peterschussheim
Last active September 4, 2016 15:19
Show Gist options
  • Save peterschussheim/0dad925d7b8140974323577c746b4134 to your computer and use it in GitHub Desktop.
Save peterschussheim/0dad925d7b8140974323577c746b4134 to your computer and use it in GitHub Desktop.
Permute Data
function perms(data) {
if (!(data instanceof Array)) {
throw new TypeError("input data must be an Array");
}
data = data.slice(); // make a copy
var permutations = [],
stack = [];
function doPerm() {
if (data.length == 0) {
permutations.push(stack.slice());
}
for (var i = 0; i < data.length; i++) {
var x = data.splice(i, 1);
stack.push(x);
doPerm();
stack.pop();
data.splice(i, 0, x);
}
}
doPerm();
return permutations;
}
var input = "abcd".split('');
var result = perms(input);
for (var i = 0; i < result.length; i++) {
result[i] = result[i].join('');
}
console.log(result);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment