11 December 2007

Array.shuffle() 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.

The shuffle function is just a slightly different version of the AS2 shuffle functions you can find on the web. Using the asterisk (*) as a datatype means that any type can be handled by the shuffle function.


package com.utils
{
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.

7 comments:

Sidney said...

Thanks! Been creating a shuffle function for a mp3 player, and it works nicely!

cheers, Sidney

Big Will... said...

Hey! Thanks a million. Just implemented it in my Video Player

Noj said...

nice work

ghkj said...

EVEN by wow gold the standards gold in wow of the worst financial buy wow gold crisis for at least wow gold cheap a generation, the events of Sunday September 14th and the day before were extraordinary. The weekend began with hopes that a deal could be struck,maplestory mesos with or without government backing, to save Lehman Brothers, America''s fourth-largest investment bank.sell wow gold Early Monday buy maplestory mesos morning Lehman maplestory money filed for Chapter 11 bankruptcy protection. It has more than maplestory power leveling $613 billion of debt.Other vulnerable financial giants scrambled maple money to sell themselves or raise enough capital to stave off a similar fate. billig wow gold Merrill Lynch, the third-biggest investment bank, sold itself to Bank of America (BofA), an erstwhile Lehman suitor,wow power leveling in a $50 billion all-stock deal.wow power leveling American International Group (AIG) brought forward a potentially life-saving overhaul and went maple story powerleveling cap-in-hand to the Federal Reserve. But its shares also slumped on Monday.

Endel Dreyer said...

Very helpful!
Thanks for sharing. :)

stelios chatzopoulos said...

There is a problem when I try to shuffle only 2 numbers, it returns always the same order!

nbap said...

Amazingly useful.
Thanks for sharing.. =)