Skip to content


I’ve been working on getting some classic Array utilities into haXe, and there’s a package now called ArrayTools on haxelib that has some common functions.

you’ll want to include the library ArrayTools inside your build file, then you can do things like:

var arr = [1,2,3];

and then:


…to randomly shuffle the array in place.

The main contribution is to include some permutation/combination style shuffling routines. They’re pretty easy to use:

trace(ArrayTools.combination(arr,2)); //return a random selection of 2 elements from the array.

Then there’s “permutators/combinators” which return Iterators. These methods won’t change the underlying structure of the given array, or copy values, but instead return an Iterator that moves through the array according to a generated index structure. This makes these routines more efficient for iterating through multiple combinations/permutations of a single array. You’ll use them like:

var itr = ArrayTools.permutators(arr);
for (i in itr){ // each unique permutation
   for (j in i){ // each element of the permutation
   trace('-'); // separate the results from different permutations with this character...

There’s a few more details:

  • The functions are based on factoradic/combinadic numbering systems, so shuffling/selection is truly random when it’s called for (or at least as random as the platform random number generator).
  • I based a lot of the code off of the examples given by James McCaffrey in his overview of permutations and combinations.
  • The functions will return Null in some instances, particularly if you specify an invalid permutation/combination to generate.  For a given array of length N, there will be N! possible permutations, so selecting a permutation higher than that number will repeat a previous permutation (negative numbers will cause an error).  For combinations of the same example array, there are N!/((N-K)! * K!) possible combinations of length K.  K values higher than N will cause errors in the combination routines, and will return Null.

I generated some documentation for the class here.

WARNING:  These functions typically don’t work if you specify the permutation of an Array larger than 12 with an integer.  In the case of permutations, there are 13! (12x11x10x9…) ~  6 Billion different ways you could shuffle an array of 13 elements, but the Integer limit on the haXe targets is around 2 Billion… so in the best case, you’d limit your options of permuting/combinations, and in the worst case, the method will crash.  The functions currently try to warn you if the index generated is invalid.  To get around this problem, you can specify the permutation using an array.  So instead of ArrayTools.permute(x,1);  You could try  ArrayTools.permute(x, [0,1,2,4,3]); (This would swap the last two elements of the array x).

%d bloggers like this: