Friday, November 28, 2008

Randomize Elements in an Array

I had to rewrite some code that randomized elements in the new Vector class (had written the code below to randomize array elements)and thought I'd post both the old array randomizer() here. nothing fancy at all...just thought might be useful to someone.


var myArray:Array =[1,2,3,4,5,6];

function randomize(arr:Array):Array{
var originalA:Array = arr;
var newA:Array=[];

while(originalA.length > 0){
var index:int = int(Math.random() * originalA.length);
var element = originalA.splice(index,1);
//splice returns an array.
newA.push(element[0]);

}

return newA;

}

trace(randomize(myArray));


Note: the splice() method of the array class actually returns an Array made up of the elements you've spliced out of the original array. This is why we need to push element[0] into the new randomized array.

No comments: