I’ve been working on a Blackjack game and have needed to do a lot of shuffling, cards that is. I’ve seen quite a few shuffling functions over the years. Here is the one I like, partly because I wrote it. Well okay I took what I liked in the others and modified them to come up with these:
public static function randomArray(src:Array):void
{
var len:uint = src.length;
for(var i:int=len-1; i>=0; i--)
{
var randIndex:uint = randomUint(0, len-1);
var temp:* = src[randIndex];
src[randIndex] = src[i];
src[i] = temp;
}
}
Vector version looks like this:
public static function randomVector(src:*):void
{
var len:uint = src.length;
for(var i:int=len-1; i>=0; i--)
{
var randIndex:uint = randomUint(0, len-1);
var temp:* = src[randIndex];
src[randIndex] = src[i];
src[i] = temp;
}
}
Here is a sample of how the vector version is used:
Randomize.randomVector(cards as Vector.<Card>);
Here is the randomUint function that it uses:
public static function randomUint(min:uint, max:uint):uint
{
return Math.random()*((max+1)-min)+min;
}
I like to call these functions a random number of times so that the deck of cards is nice and shuffled. Enjoy!