AS3 Array Shuffle
There are alot of ways to shuffle an array in AS3, ranging from swapping repeatedly the elements to using the sort function with a random sorter, but the most convenient way I’ve found was to simply splice a random element from the former array to the new shuffled array while the former array has elements.
DaveOnCode has a nice implementation of this method, pasted here:
var arr2:Array = [];
while (arr.length > 0) {
arr2.push(arr.splice(Math.round(Math.random() * (arr.length - 1)), 1)[0]);
}
Edit: Although small and convenient, this method is not the fastest way of shuffling an array, check out the comments for more info.
April 17th, 2009 at 2:16 pm
Thank you for the quote! :)
June 15th, 2009 at 2:58 pm
Absolutly perfect, thanks a lot!
July 13th, 2009 at 8:36 am
Thanks! Will need this :)
September 9th, 2009 at 5:47 pm
Wow. Brilliant. Best, cleanest, and fastest array shuffle I have found. Thank you for sharing this.
March 18th, 2010 at 8:51 am
Excellent!
March 22nd, 2010 at 2:00 am
nice thank u!
March 23rd, 2010 at 2:29 pm
It would probably be a tad faster like this:
var len:int = arr.length;
var arr2:Array = new Array(len);
for(var i:int = 0; i<len; i++)
{
arr2[i] = arr.splice(int(Math.random() * (len - i)), 1)[0];
}
March 29th, 2010 at 9:28 pm
Ta buddee :)
May 14th, 2010 at 2:37 pm
hi
nice way but it’s not the fastest
take a look http://mrsteel.wordpress.com/2007/06/15/randomize-array-shuffle-an-array-in-flash/
shuffle by slice is one of slowest methods actually
May 14th, 2010 at 2:53 pm
Thanks for that info MrSteel, good to have that reference here