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){

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.


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

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.. =)

Pier said...

why use super.push() instead of simply this.push()

Anonymous said...

Obrigado. era isto que eu procurava...

Joan said...

Hi, I think this version of the code works fine, even for two elements:

//No assignation needed.
public function shuffle(startIndex:int = 0, endIndex:int = 0):ExtendedArray {

var cont:uint;
var randomNumber:uint;
var tmp:*;

if (endIndex == 0) {
endIndex = this.length;
for (cont = startIndex; cont<endIndex; cont++) {
randomNumber = uint(Math.random() * endIndex) + startIndex;
tmp = this[cont];
this[cont] = this[randomNumber];
this[randomNumber] = tmp;
return this;