Randomize or shuffle an array

10,102

Solution 1

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

Solution 2

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.

Share:
10,102
redconservatory
Author by

redconservatory

Updated on June 04, 2022

Comments

  • redconservatory
    redconservatory almost 2 years

    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++) {
                var item:Number = Math.floor(Math.random() * myList.length-1) + 1;
                myRandomList.push(item);
          }
    

    The only thing is, I'd like myRandomList to not have any duplicate numbers...is there a way to select a random number from the first list and then SUBTRACT it so I don't select that number twice?

    UPDATE:

    I just saw this method of shuffling an array from shadetyler.blogspot.com/2008/12/array-shuffle-as3.html

    Array.prototype.shuffle = function(){
    for(var i = 0; i < this.length; i++){
    var a = this[i];
    var b = Math.floor(Math.random() * this.length);
    this[i] = this[b];
    this[b] = a;
    }
    

    However, is there a way to rewrite this as a function? }

  • redconservatory
    redconservatory about 13 years
    This is great! But the link doesn't have an Actionscript 3 example...can you elaborate a bit more?
  • phwd
    phwd about 13 years
    @redconservatory you are just switching spots within the array so no need to push elements into it. As for the duplicates if a==i then there is no change.