skip to content

Random permutation of array

Here is the code snippet for generating random permutation of array:

var a:Array = new Array( 1, 2, 3, 4, 5, 6, 7, 8, 9 );

trace( "Array: " + a );

for ( var i:uint = 0; i < a.length; ++i )
{
    var j:int = Math.random()*i;
    var j:int = Math.random()*( i + 1 );

    // Swap a[i] and a[j]
    var temp:* = a[j];
    a[j] = a[i];
    a[i] = temp;
}

trace( "Permutation: " + a );

Update: fixed bug with finding index of item to swap – thanks for pointing that out Kevin!

You can leave a response, or trackback from your own site.

2 Responses


  1. Kevin Canini Says:

    I don’t think your code generates random permutations. I believe you need to change the line:

    var j:int = Math.random() * i;

    to:

    var j:int = Math.random() * (i+1);

    Otherwise, the last element of the array can never end up in its original position.

  2. micah Says:

    what is the operator * in var temp:*



Leave a Reply