Created
November 18, 2013 16:10
-
-
Save konijn/7530454 to your computer and use it in GitHub Desktop.
Permute
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
/* Permute will give all permutations for the provided array ( sourceSet ) | |
do not provide usedSet nor permutationSet | |
Based on http://stackoverflow.com/a/9960925/7602 | |
*/ | |
function permute( sourceSet , usedSet , permutationsSet ) { | |
permutationsSet = permutationsSet || []; | |
usedSet = usedSet || []; | |
for (var i = 0; i < sourceSet.length; i++) { | |
usedSet.push( sourceSet.splice(i, 1)[0] ); | |
if (!sourceSet.length) | |
permutationsSet.push(usedSet.slice()); | |
permute(sourceSet, usedSet , permutationsSet); | |
sourceSet.splice(i, 0, usedSet.pop()); | |
} | |
return permutationsSet | |
} | |
//Test | |
console.log( permute( "abc".split("") ) ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment