Friday, December 12, 2008

Array Shuffle AS3

When working on shuffling arrays for games we are working on, I wanted to write something that would be efficient and quick. I had previously written a method using the Array push and splice methods and was short, but when testing that against my new function, found that the push, splice methods use a lot of memory and are about half as slow as my final solution. (Please test this if you aren't convinced) The final solution is posted here using the prototype extension (I am still not sure whether or not the prototype usage is being deprecated):

Array.prototype.shuffle = function(){
    for(var i = 0; i < this.length; i++){
        var a = this[i];
        var b = Math.floor(Math.random() * this.length);
        this[i] = this[b];
        this[b] = a;
    }
}

This can be modified into a regular function by changing it to pass an array by argument and then modifying the passed in array object. If you have questions, just let me know.

3 comments:

Brandon West said...

This was very well written. Thanks, it really helped on my FlashCard Application.

Davide Zanotti said...

This is my own solution: http://www.daveoncode.com/2009/01/08/implementing-arrayshuffle-in-actionscript/

It's only 3 lines of code and it works fine :)

Michael Corrigan said...

While your code has only 3 lines, it actually runs slower. The amount of time is takes for the array functions of splice and push is considerably more and they use up more memory. Originally I was using a method similar to the one you posted but decided to try and optimize it.
Although I must say, you have done a good job for finding a short solution.