Home » ActionScript 3.0, Flash CS4, Flash CS5

AS3 Randomize an array order in Flash

17 September 2012 No Comment
Share on Facebook

We may want to supply different number sequence may be randomized to our code in order to behave different in situation. Since we dont have array shuffle function in as3. We have to write our code to achieve the effect.

So I have given different ways of acheiving randomized array in as3. The most important is without using looping statement.

Below is examples of functions which randomizes the order of the elements in the array.

Randomize an array  as3 without looping statement

var rawArr:Array = ["1","2","3","4","5"];
trace(randomizeArray(rawArr));
function randomizeArray(myArray:Array):Array
{
	myArray.sort(function(){ return Math.random()-0.5; }); 
	return myArray;
}

Randomize an array as3 using for loop

var rawArr:Array = ["1","2","3","4","5"];
trace(randomizeArray(rawArr));
function randomizeArray(myArray:Array):Array
{
	for (var i:uint = 0; i < myArray.length; i++)
	{
		var rand:uint = int(Math.random() * myArray.length);
		myArray.push( myArray.splice( rand, 1 )[0] );
	}
	return myArray;
}

Randomize an array as3 using while loop

var rawArr:Array = ["1","2","3","4","5"];
trace(randomizeArray(rawArr));
function randomizeArray(array:Array):Array
{
	var newArray:Array = new Array();
	while (array.length > 0)
	{
		newArray.push(array.splice(Math.floor(Math.random()*array.length), 1));
	}
	return newArray;
}

Conclusion:

randomizeArray function takes the entire array and randomizes the position of the elements in there. If you have better function please share as comments.

GET THE UPDATES VIA EMAIL

We don't share your email anywhere, grab our rss via feedburner