Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@dmmarmol
Created April 4, 2017 14:38
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 dmmarmol/cb75373a0fe4a366ce7ff3b929ffafbf to your computer and use it in GitHub Desktop.
Save dmmarmol/cb75373a0fe4a366ce7ff3b929ffafbf to your computer and use it in GitHub Desktop.
Create permutations from two or more given list
/**
* 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