Friday, July 15, 2011

AS3 Code: Randomize Array

var rand:Array = [0,1,2,3];

trace(randomize(rand));
//2,0,3,1 for example

function randomize(arr:Array):Array{
    var temp1:uint;
    var temp2:uint;
    var temp3:uint;
    for(var i:uint = 0; i < arr.length; i++){
        temp1 = Math.floor((Math.random() * (arr.length - i)) + i);
        temp2 = arr[i];
        temp3 = arr[temp1];
        arr[i] = temp3;
        arr[temp1] = temp2;
    }
    return arr;
}


A big thanks to my coworker Ryan for showing me this fantastic code!



0 comments:

Post a Comment