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.

10 Responses to “AS3 Array Shuffle”

  1. DaveOnCode Says:

    Thank you for the quote! :)

  2. turtlebite Says:

    Absolutly perfect, thanks a lot!

  3. Funky Clouds Says:

    Thanks! Will need this :)

  4. Jo Albright Says:

    Wow. Brilliant. Best, cleanest, and fastest array shuffle I have found. Thank you for sharing this.

  5. Özgür Says:

    Excellent!

  6. xxxxGame Says:

    nice thank u!

  7. philtre Says:

    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];
    }

  8. chichilatte Says:

    Ta buddee :)

  9. MrSteel Says:

    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

  10. Flassari Says:

    Thanks for that info MrSteel, good to have that reference here

Leave a Reply

Spam protection by WP Captcha-Free