Quantcast
Channel: Designscripting
Viewing all articles
Browse latest Browse all 22

AS3 Randomize an array order in Flash

$
0
0

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.

Related posts:

  1. Use Splice to delete all elements in an Array
  2. Remove Duplicate Array Elements
  3. Convert string to a character array + Flash Actionscript AS3
  4. Maths and Actionscript 3 code | Using as3 with math
  5. Search Manager Suggest tool(AS3)

Viewing all articles
Browse latest Browse all 22

Trending Articles