Pages

Monday, June 24, 2013

AS3 Random Numbers Generator

Here's an AS3 random numbers generator that I wrote a while back, and I thought I'd share it. I explain how to use it after the code.

var allNumbers:Array = new Array();
var randomNumbers:Array = new Array();
var highest:int = 55;
var pick:int = 6;

for (var i:int = 1; i <= highest; i++)
{
    allNumbers[i] = i;
    if (i == highest)
    {
        getRandomNumbers();
    }
}

function getRandomNumbers():void
{
    for (var i:int = 0; i < pick; i++)
    {
        var rand:int = Math.ceil(Math.random() * (allNumbers.length - 1));
        randomNumbers[i] = allNumbers.splice(rand,1);
        if (i == pick - 1)
        {
            trace(randomNumbers.sort(Array.NUMERIC));
        }
    }
}

// For more ActionScript 3 tutorials, visit http://www.trainingtutorials101.com


Here's how it works:

  1. The highest variable allows to to specify the highest random number that can be chosen. So for example, if you assign a value of 55, then the highest random number you can get will be 55.
  2. The pick variable lets you specify how many random numbers to choose. So for example, if you assign a value of 6, then 6 random numbers will be chosen.
  3. The code is set so that the lowest random number you can get is 1, and that each number only appears once.