Skip to content

Instantly share code, notes, and snippets.

@konijn
Created November 18, 2013 16:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save konijn/7530454 to your computer and use it in GitHub Desktop.
Save konijn/7530454 to your computer and use it in GitHub Desktop.
Permute
/* 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