OK. This is a cool thing. A solution I got from a friend.
Here's the summary: You start with an array. Push things into it. Make another empty array tempArray or whatever, Then you generate a random integer 'r' in the range of 0 to the last index of original array. You use array.splice() to take the array index 'r' and push it onto the tempArray.
splice returns an array and actually removes the element from the original array. so you loop until the original array is empty. That's it. You can assign the variable name of of the original to point to the temp array.
Here's the code for creating an array of a deck of cards, each with a value of 0 through 51. And then shuffle it.
var array:Array = new Array(52);
for ( var i:Number = 0; i < 5; i++ )
this.array.push( i );
so now you have an ordered array containing the numbers 0 - 51.
I suggest a shuffle() function. You could call it randomize or whatever. if you have it return an Array, you can just assign the function results right into a variable.
here's my shuffle - pay close attention to array.splice();
public function shuffle():Array
{
var temp_array:Array = new Array(0); // holder for shuffled cards
while ( array.length > 0 )
temp_array.push( array.splice( Math.floor( Math.random() * array.length ), 1 )[0] );
array = temp_array; // optionally copy the reference
return array;
}
OK I know that that single line of code is confusing to look at, but it's an abbreviated way to do several things at once. array.splice() returns an array containing the elements from index n through x indexes.
the signature:
from the AS2 Docs:
splice(startIndex:Number, [deleteCount:Number], [value:Object]) : Array
so, what I'm doing is pushing on to the new array, index 0 of the array returned from splicing a random index with a count of 1. I know how screwy that sounds.
you could do it like this - expanded:
var tempArray:Array = new Array();
while ( array.length > 0 )
{
var randomIndex:Number = Math.floor( Math.random() * array.length ), 1 );
var splicedArray:Array = array.splice( randomIndex, 1);
var item:Number = splicedArray[0];
tempArray.push( item );
}