Permutations in AS3
I needed a method to find permutations of elements within an Array, for a little something that I’m working on. I couldn’t find one ‘off the shelf’, and while it’s easy enough to do yourself, it’s easier to use someone else’s. If you’re not very familiar with the concept of permutations, please be sure to read the method header if you intend to use this method.
/**
* Finds the permutations of an array by recursively permutating sub-arrays
*
* WARNING! For n elements there are n! permutations - ie. if you have
* 6 elements in your array you will find returned an array containing
* 6*5*4*3*2 = 720 arrays of your elements. 10 elements returns an
* array containing more than 3.5 million arrays, which is not
* recommended.
*
* @param elements The elements to be permutated
* @return An array of all of the permutations of the elements in the array.
*/
public function permutate(elements:Array):Array
{
if (elements.length == 1)
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--)
{
tmp = elements.slice(0, i).concat(elements.slice(i + 1, length));
sub = permutate(tmp);
j = sub.length;
while (j--)
{
tmp = [elements[i]].concat(sub[j]);
permutations.push(tmp);
}
}
return permutations;
}
-
http://twitter.com/alecmce alecmce
-
Marc Tanenbaum
-
Marc Tanenbaum
-
http://alecmce.com Anonymous
-
http://alecmce.com alec
-
Manre
-
Manre
-
Manre


