Created
April 30, 2015 03:15
-
-
Save mbenford/51316d460887e93676c2 to your computer and use it in GitHub Desktop.
Generate all permutations of the given set
This file contains hidden or 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 getPermutations(set) { | |
var result = []; | |
permutate(set); | |
return result; | |
function permutate(set, subset) { | |
if (!subset) subset = []; | |
if (set && !set.length) { | |
result.push(subset); | |
return; | |
} | |
for (var i = 0; i < set.length; i++) { | |
var newSet = set.slice(0, i).concat(set.slice(i + 1, set.length)); | |
var newSubset = subset.concat(set.slice(i, i + 1)); | |
permutate(newSet, newSubset); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment