Randomizing an Array
Posted in Actionscript, Flash on May 25th, 2009 by Sandro Haag – 4 CommentsHi!
Here is a simple example of how to sort the items of an Array and get a randomized Array:
function sortArray (original:Array) : Array
{
var temp:Array = original;
var sort:Array = [];
while (temp.length > 0)
{
var r:int = Math.random() * temp.length;
sort.push(temp[r]);
temp.splice(r, 1);
}
return sort;
}
Now, just execute the method, passing as parameter the Array that you want to randomize.
var original:Array = [0, 1, 2, 3, 4];
var randomized:Array = sortArray(original);
trace(”result: ” + randomized); // result: 3, 1, 4, 0, 2
That’s it!