Array shuffling in ActionScript3

By | 21 August, 2013

Been wanting to add this post for a while. Pretty simple, really.

So imagine you have an array:


It can be any size, obviously. And you want to change the position of its items. Several ways to do so – like splicing the array, but i dont recommend it because theres a loss in speed -, but i found the following to be the fastest and simplest:

private function (lista:Array):Array{
    var total:int = lista.length;
    var rand:int = Math.floor(Math.random()*total);
    var t:int;
    for(var j:int=0;j<total;j++){
        lista[j] = t;
    rand = Math.floor(Math.random()*total);
    return lista;

What this does: it navigates the array positions sequentially and replaces the item on the current position(j) with one from a random position(rand). Please regard this as the main idea, since you can add a few bells and whistles to it if you want (like check if the random position is the same as the current one, or even make a couple of passes to the full length of the array to “guarantee” more randomness (dont go adding loops to randomize more, you will lose the purpose)).

Hope it helped. I typed this from heart, so please forgive any mistakes and if you find any, please let me know in the comments below.