Skip to content

Instantly share code, notes, and snippets.

@alecmce
Created May 13, 2013 16:55
Show Gist options
  • Save alecmce/5569760 to your computer and use it in GitHub Desktop.
Save alecmce/5569760 to your computer and use it in GitHub Desktop.
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