Created
April 4, 2017 14:38
-
-
Save dmmarmol/cb75373a0fe4a366ce7ff3b929ffafbf to your computer and use it in GitHub Desktop.
Create permutations from two or more given list
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
/** | |
* Create permutations from two or more given list | |
* Based on Heap's Algorithm | |
*/ | |
function permutations() { | |
var r = [], arg = arguments, max = arg.length-1; | |
function helper(arr, i) { | |
for (var j=0, l=arg[i].length; j<l; j++) { | |
var a = arr.slice(0); // clone arr | |
a.push(arg[i][j]); | |
if (i==max) | |
r.push(a); | |
else | |
helper(a, i+1); | |
} | |
} | |
helper([], 0); | |
return r; | |
} | |
console.log(permutations(["4",5,"6"], [1,2], [7,8,9])) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment