September 1, 2009

ActionScript 3: Shuffle/randomize any Array

A quick little function for randomizing/shuffling an Array that contains objects or primitive of any data type:

public static function randomizeArray( arr:Array ):void
{
for( var i:int = 0; i < arr.length; i++ )
{
var tmp:* = arr[i];
var randomIndex:int = Math.round( Math.random() * ( arr.length - 1 ) );
arr[i] = arr[randomIndex];
arr[randomIndex] = tmp;
}
}

You can see that it crawls through an Array, swapping each position with another, random position in the Array.

1 comment:

  1. This function is not uniformely distributed, use Math.floor in stead Math.round

    ReplyDelete