Last active
May 20, 2020 12:52
-
-
Save textarcana/5737478 to your computer and use it in GitHub Desktop.
Array permutation
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
/*jslint sloppy:true, white:true, vars:true, plusplus:true */ | |
var permutation = function (collection){ | |
var current, | |
subarray, | |
result = [], | |
currentArray = [], | |
newResultArray = []; | |
if (collection.length){ | |
current = collection.shift(); | |
result = permutation(collection); | |
currentArray.push(current); | |
result.map(function(list) { | |
newResultArray.push(list.slice(0)); | |
list.push(current); | |
}); | |
result.push(currentArray); | |
result = result.concat(newResultArray); | |
} | |
return result; | |
}; | |
console.log(permutation(['a','b','c','d']) | |
.join('\n')); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Another implementation: https://gist.github.com/md2perpe/8210411