Randomize or shuffle an array

后端 未结 2 656
情歌与酒
情歌与酒 2020-12-12 01:03

Say I have an array:

myList:Array = new Array();
myList = [1,2,3,4,5,6,7,8,9];

myRandomList:Array = new Array();

for (var i:uint = 0; i < myList; i++) {         


        
2条回答
  •  抹茶落季
    2020-12-12 01:33

    The title says shuffle an array so if you are looking for an ideal shuffle you may want the Fisher–Yates algorithm that is unbiased.

    So if you wanted to use/keep your original, you would initialize myRandomList

    var myRandomList: Array = new Array( myList.length );
    

    Then create a random number with the range say a and then swap myRandomList[a] with myRandomList[i] where i is the current element.

    // Random number
    var a = Math.floor(Math.random() * myList.length);
    // A swap
    myRandomList[i] = myRandomList[a];
    // put whatever is in index a in the ith position
    myRandomList[a] = myList[i];
    // restore whatever was in the ith position to index a
    

提交回复
热议问题