-
-
Save frutik/e942f0bb6b948f86b1c052db85a5c970 to your computer and use it in GitHub Desktop.
Function for generating permutations of a list.
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
function permutations(list) | |
{ | |
// Empty list has one permutation | |
if (list.length == 0) | |
return [[]]; | |
var result = []; | |
for (var i=0; i<list.length; i++) | |
{ | |
// Clone list (kind of) | |
var copy = Object.create(list); | |
// Cut one element from list | |
var head = copy.splice(i, 1); | |
// Permute rest of list | |
var rest = permutations(copy); | |
// Add head to each permutation of rest of list | |
for (var j=0; j<rest.length; j++) | |
{ | |
var next = head.concat(rest[j]); | |
result.push(next); | |
} | |
} | |
return result; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment