This Gist was automatically created by Carbide, a free online programming environment.
Last active
September 4, 2016 15:19
-
-
Save peterschussheim/0dad925d7b8140974323577c746b4134 to your computer and use it in GitHub Desktop.
Permute Data
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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