Joe's Blog

line

A blog by Joe Billman about programming, and other stuff

line

Archive for December, 2010

Random Vector and Random Array Functions

Posted on: December 7th, 2010 by Joe

line No Comments

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!


Warning: Use of undefined constant Y - assumed 'Y' (this will throw an Error in a future version of PHP) in /homepages/16/d145171736/htdocs/php/footer.php on line 1