`

Sunday, September 26, 2010

Shuffle Array in AS3

Here's an AS3 class called ExtendedArray that unsurprisingly extends the functionality of the Array class. One important thing to note is that it is a dynamic class. This allows you to add properties and methods to the base class at runtime.

Another thing to note is looping through the optionalArgs (or "rest" arguments as they're known) and using super.push() to populate the Array in the constructor. Simply using super(optionalArgs) would create an array within the Array i.e. a 2d array.

here is the code.


package 
{
    dynamic public class ExtendedArray extends Array;
    {
        public function ExtendedArray(... optionalArgs)
        {
            for each (var value:* in optionalArgs)
            {
                super.push(value);
            }
        }

        public function shuffle(startIndex:int = 0, endIndex:int = 0):Array
        {
            if (endIndex==0)
            {
                endIndex=this.length-1;
            }
            for (var i:int = endIndex; i>startIndex; i--)
            {
                var randomNumber:int=Math.floor(Math.random()*endIndex)+startIndex;
                var tmp:* =this[i];
                this[i]=this[randomNumber];
                this[randomNumber]=tmp;
            }
            return this;
        }
    }
}


You could add many more functions to this to increase the functionality of the base Array class.

No comments: