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++) {
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
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.