Randomize Array – Shuffle an array in Flash

After I’ve post solution for shuffling an array with Array.sort method which purspose was to just show what a sort function can be used for I am now posting solution which is best for doing a shuffle of an array. There were few discussions about it on the web.

I’ve made a little test to demonstrate speed of testing

There are 4 methods
First one is Array.sort, second is using splice and last two are basiclly the same, one beign prototype for array and second is plain function which returns an array.

Speed test returned following results (could vary a little bit but not spectacular):

For 1500 elements
Sort – 2216 ms
Splice – 8300 ms
Prototype – 16 ms
Return Function -15 ms

You can take test file here

Prototype function and return function code is :

Array.prototype.mixElements = function() {
var _length:Number = this.length, rn:Number, it:Number, el:Object;
for (it = 0; it<_length; it++) {
el = this[it];
this[it] = this[rn = random(_length)];
this[rn] = el;
}
}

function mixArray(array:Array):Array {
var _length:Number = array.length, mixed:Array = array.slice(), rn:Number, it:Number, el:Object;
for (it = 0; it<_length; it++) {
el = mixed[it];
mixed[it] = mixed[rn = random(_length)];
mixed[rn] = el;
}
return mixed;
}

Code is only for AS2 but it can be easily turned into AS3 code

About these ads

33 Responses to “Randomize Array – Shuffle an array in Flash”


  1. 1 JenUnderscore_ January 17, 2008 at 8:29 pm

    Thanks! This was very helpful :)

  2. 2 Seth February 13, 2008 at 2:52 pm

    I’m a novice when it comes to actionscript. I understand I can copy paste these examples, but I’m more interested in the logic behind what is going on. Is there anyone who has the time to write an explanation for at least one of the examples so I can apply this to anything I might need to do. Thank you!

  3. 3 Miquel Ozke February 19, 2008 at 11:29 am

    AS3 version (sacrifying some millisecond to make it easier to read)

    private function randomArraySort(_array:Array):Array {
    var _length:Number = _array.length;
    var mixed:Array = _array.slice();
    var rn:Number;
    var it:Number;
    var el:Object;
    for (it = 0; it<_length; it++) {
    el = mixed[it];
    rn = Math.floor(Math.random() * _length);
    mixed[it] = mixed[rn];
    mixed[rn] = el;
    }
    return mixed;
    }

  4. 5 Tonypee February 27, 2008 at 5:27 am

    Slightly smaller AS3 version:

    function randomizeArray(array:Array):Array {
    var l:Number = array.length-1;
    for (var it = 0; it<l; it++) {
    var r = Math.round(Math.random()*l)
    var tmp = array[it];
    array[it] = array[r];
    array[r] = tmp;
    }
    return array;
    }

  5. 6 meggannn March 6, 2008 at 2:01 am

    what is a arraY??? PLZ CAN U TELL ME PLZ I NEED TO KNOW FOR A TEST OR HOMEWORK RATHER!!!! by meggannn

  6. 7 tori March 27, 2008 at 5:19 pm

    excellent. many thanks to you.

  7. 8 Anders June 11, 2008 at 10:53 am

    @Tonypee: You code modifies the original array, and sometimes returns an extra empty element.
    My version look like this:
    private function randomizeArray($array:Array):Array {
    var returnArray:Array = new Array();
    var orgArray:Array = $array.slice();
    while (orgArray.length > 0) {
    var r:uint = Math.floor(Math.random()*orgArray.length);
    returnArray.push(orgArray.splice(r, 1));
    }
    return returnArray;
    }
    It removes a random element from the array, and add it to another array. And keeps going until all elements have been randomized.

  8. 9 Brighton flash ninja June 29, 2008 at 9:01 pm

    This is really useful thanks, i was also having problems with empty elements causing my array to have random errors though

  9. 10 FJGamer February 15, 2009 at 12:38 am

    I was making a randomized questions quiz with randomized answers (including the correct answer for each question and four random answers), and I kept seeing it repeat answers. It was mind-boggling, but I figured it out. I was checking for the value rather than the index in the splice function. Took me hours to figure out what I was doing wrong! XD

  10. 11 Hoss March 19, 2009 at 1:56 am

    @Anders : Your code creates a multi-dimensional array because you are pushing the return of the splice which itself is an array. Here’s the fix.

    private function randomizeArray(srcArray : Array) : Array {
    var returnArray : Array = new Array();
    var orgArray : Array = srcArray.slice();
    while (orgArray.length > 0) {
    var r : uint = Math.floor(Math.random() * orgArray.length);
    returnArray.push(orgArray.splice(r, 1)[0]);
    }
    return returnArray;
    }

  11. 12 Tom Anderson March 27, 2009 at 6:55 pm

    Actually, IMO, the Prototype function in the post above is not truly random, and is in fact what is called a poorly implemented Knuth shuffle…

    http://en.wikipedia.org/wiki/Shuffle#Poorly_implemented_Knuth_shuffles

    To achieve true randomness, the the cards must be randomly selected from the cards that have not yet been selected, rather than switching the card with any of the other cards, some of which have likely been switched already.

    The correction to make is simple:
    USE:
    mixed[it] = mixed[rn = it + random(_length - it)];

    NOT:
    mixed[it] = mixed[rn = random(_length)];

  12. 13 Tom Anderson March 27, 2009 at 7:37 pm

    Sorry for multiple posts, but I’m excited to be getting times of under 1 ms for 1500 value arrays…

    Using “while” instead of “for”, as in the following function, reduces the processing time from 4 ms to 1 ms! So the stats are (Methods 1-4 are original, Method 5 is the while loop):

    Method 1, time: 718
    Method 2, time: 1957
    Method 3, time: 3
    Method 4, time: 4
    Method 5 (while), time: 1, sometimes 0!

    /////////////////////////

    function mixArray(array:Array):Array {
    var _length:Number = array.length, mixed:Array = array.slice(), rn:Number, it:Number, el:Object;
    while (it < _length) {
    el = mixed[it];
    mixed[it] = mixed[rn = it + random(_length - it)];
    mixed[rn] = el;
    it++;
    }
    return mixed;
    }

  13. 15 me November 13, 2009 at 1:42 am

    @Tom Anderson: Yeah it gives you 0-1ms cause it is undefined, so the code doesn’t even run…

    You need to change this line
    var _length:Number = array.length, mixed:Array = array.slice(), rn:Number, it:Number = 0, el:Object;

  14. 16 andy November 13, 2009 at 11:00 am

    Thank you Mr. Steel for the elegant prototype-based solution!

  15. 17 Daniel Goulding May 21, 2010 at 1:43 am

    Thanks for blog article & comments.

    I thought I’d throw my hat into the ring. I took the shuffle function and have tried to optimise it. This is my effort and I get pretty good speed test results with it.

    function Shuffle( array:Array ):Array{
    var n:int = array.length, shuffled:Array = array.concat(), element:*, i:int = 0, r:int;
    while( i < n ){
    element = shuffled[ i ];
    r = Math.floor( Math.random() * n );
    shuffled[ i ] = shuffled[ r ];
    shuffled[ r ] = element;
    i++;
    }
    return shuffled;
    }

  16. 18 Loffe Loftsson August 17, 2010 at 7:31 am

    //This is the best way of doing stuff.
    function mixArray(array:Array):Void {
    var i = array.length,el:Object,rn:Number;
    while (i–) {
    el = array[i];
    array[i] = array[rn = random(i)];
    array[rn] = el;
    }
    }

  17. 19 MrSteel August 19, 2010 at 1:44 am

    this is all just retyping variations of same method

  18. 20 Hai Phan November 4, 2010 at 8:24 am

    Well, here it is again! But mine is the best I’m sure :D

    function shuffle(array) {
    var n = array.length;
    while (n > 1) {
    n–;
    var k = Math.floor(Math.random()*(n + 1));
    var tmp = array[k];
    array[k] = array[n];
    array[n] = tmp;
    }
    return array;
    }

  19. 21 Agustín Amenabar November 18, 2010 at 11:01 pm

    Thanks! a fast code, and even better, fast to find on google :)
    way faster than firing CS5′s help thing.

  20. 22 Ziggi March 1, 2011 at 12:18 am

    @Hai Phan

    Why not:

    function shuffle(array) {
    var n = array.length;
    while (n > 1) {
    var k = Math.floor(Math.random()*(n));
    n–;
    var tmp = array[k];
    array[k] = array[n];
    array[n] = tmp;
    }
    return array;
    }

    But anyway – thi ain’t good shuffle at all – your entropy is decreasing with each step down.

  21. 23 Ziggi March 1, 2011 at 1:10 am

    This is good one:

    function shuffle(array:Array):Array{
    var n:uint = array.length;
    var temp:Array = new Array();
    while(n > 1){
    temp.push(array[Math.floor(n * Math.random())]);
    n–;
    }
    return temp;
    }

    • 24 Ziggi March 1, 2011 at 1:35 am

      Sorry, it should read:

      function shuffle(array:Array):Array{
      var n:uint = array.length;
      var temp:Array = new Array();
      while(n > 0){ // <- HERE WAS THE ERROR !!!
      temp.push(array[Math.floor(n * Math.random())]);
      n–;
      }
      return temp;
      }

      • 25 Ziggi March 1, 2011 at 1:41 am

        Oups – sorry – I see my there is a stuid flaw in my concept :)
        This must be due to little sleep today – sorry again – the right code is this one:

        function shuffle(array) {
        var n = array.length;
        while (n > 1) {
        var k = Math.floor(Math.random()*(n));
        n–-;
        var tmp = array[k];
        array[k] = array[n];
        array[n] = tmp;
        }
        return array;
        }

  22. 26 jane March 19, 2012 at 8:58 am

    can i have some codes on how to random example a given 10 question.tnx..

  23. 27 daleok16 April 6, 2013 at 6:47 pm

    greatest nude site.s baixar dominium men play blue highway ropa transparente sexy porn link on mediafire video amateur de sex francais indian overseas bank branches xiaolin showdown hentai
    http://asses.sexblog.pw/?terry
    photo plus belle blonde black download data structure throat c girls sucking dick on cam backstreet boys drowning bbw lesbian lezdom petgirls depositfiles kdv boys cms to feet conversion


  1. 1 ptolemy.co.uk » Blog Archive » Shuffling Arrays 2 Trackback on June 15, 2007 at 6:19 pm
  2. 2 ptolemy.co.uk » Blog Archive » Shuffling Arrays 3 Trackback on June 16, 2007 at 2:29 pm
  3. 3 Random array in AS2 & AS3 example using sort « Cyberspace Nova Trackback on June 28, 2007 at 8:02 am
  4. 4 Random Sort Trackback on February 28, 2009 at 1:03 am
  5. 5 how to make a square query « HKM Experimental Lab Trackback on February 12, 2010 at 2:11 pm
  6. 6 2010 in review « Cyberspace Nova Trackback on January 2, 2011 at 11:37 pm

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s




Info

Blog of Aleksandar Gvozden Technical director of MADEBYPLAY

Welcome and enjoy... more updates coming soon!

Catch me on
Twitter
LinkedIn
Facebook


CU3ER - 3D Image Slider

Twitter

Tags


Follow

Get every new post delivered to your Inbox.

%d bloggers like this: