1 (edited by gingerbeardman 2008-03-02 15:21:46)

Topic: How to Array.shuffle() in ActionScript 2.0?

What method do people use to randomise/shuffle (an array) on the Chumby?

Thanks,
matt

Re: How to Array.shuffle() in ActionScript 2.0?

Just pick two random indices and swap their contents a bunch of times.

var numSwaps:Number = 20;
var max:Number = myArray.length;
var i:Number;
var temp:Object;
var alpha:Number;
var beta:Number;

for (i=0; i<numSwaps; ++i) {
    alpha = random(max);
    beta = random(max);
    temp = myArray[alpha];
    myArray[alpha] = myArray[beta];
    myArray[beta] = temp;
}

3 (edited by gingerbeardman 2008-03-02 18:55:10)

Re: How to Array.shuffle() in ActionScript 2.0?

I eventually went with the code below, making sure the function is declared before using it:

// Array.shuffle() capability
Array.prototype.shuffle = function() {
    var len = this.length;
    var rand, temp, i;
    for (i=0; i<len; i++) {
        rand = random(len);
        temp = this[i];
        this[i] = this[rand];
        this[rand] = temp;
    }
};

Thanks to a quick Google

Re: How to Array.shuffle() in ActionScript 2.0?

The problem with that function is that it only runs through the array once - you may want to shuffle a bit more than that to  help ensure randomness (particularly on short arrays).

Re: How to Array.shuffle() in ActionScript 2.0?

waxpraxis wrote:

The problem with that function is that it only runs through the array once - you may want to shuffle a bit more than that to  help ensure randomness (particularly on short arrays).

Actually, that's not necessary - mathematically, you won't be any more random by doing more than this single loop.

Another slight variation is Fisher-Yates:

Array.prototype.shuffleFY = function(o){
    for (var j, x, i = this.length; i; j = int(Math.random() * i), x = this[--i], this[i] = this[j], this[j] = x);
    return this;
};

Re: How to Array.shuffle() in ActionScript 2.0?

Nice and compact, I like it.