Randomize or shuffle an array

后端 未结 2 655
情歌与酒
情歌与酒 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
    
    0 讨论(0)
  • 2020-12-12 01:48

    I haven't done much actionscript, but if there's a resizable array class, you could randomly transfer the data... Ex:

    array from array to

    for loop over from with iterator j. Pre-generate this number, because it will change i = get a random index in from to[j]=from[i] remove from[i]

    If there's no size mutable array class, you can always do the random swapping

    array theArray

    rand = a random number for rand idx1, idx2 -> set to random numbers temp = theArray[idx1] theArray[idx1] = theArray[idx2] theArray[idx2] = temp

    something like that that's just psudo code.

    0 讨论(0)
提交回复
热议问题