Created
May 13, 2013 16:55
-
-
Save alecmce/5569760 to your computer and use it in GitHub Desktop.
Answering Zsolt's question here: http://alecmce.com/as3/permutations-in-as3#comment-895972434
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
public function permutate(elements:Array, limit:int):Array | |
{ | |
if (elements.length == 1 && limit > 0) | |
return [elements[0]]; | |
var permutations:Array = []; | |
var length:int = elements.length; | |
var i:int, j:int; | |
var tmp:Array; | |
var sub:Array; | |
i = length; | |
while (i-- && permutations.length < limit) | |
{ | |
tmp = elements.slice(0, i).concat(elements.slice(i + 1, length)); | |
sub = permutate(tmp); | |
j = sub.length; | |
while (j-- && permutations.length < limit) | |
{ | |
tmp = [elements[i]].concat(sub[j]); | |
permutations.push(tmp); | |
} | |
} | |
return permutations; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment