How do you generate a random number within a given limit using the ActionScript?

14,897

Solution 1

So if I understand well, you want something like a next(low, high) method. AS3 contains already a Math.random() method what generates a floating point random number from 0 to 1.

In order to restrict it, you need to do something like this:

var low:Number = 1;
var high:Number= 100;
var result:Number = Math.floor(Math.random() * (1 + high - low)) + low;

The code is quite straightforward, basically you're multiplying the difference between high & low and adding the low. Overall result is floored using Math.floor() to be sure it's an integer.

Hope it helps!

Solution 2

To get a number from 0 to 100, you can use:

Math.random()*100;

To get a number from from 10 to 110 use:

Math.random()*100 + 10;
Share:
14,897
Vinod
Author by

Vinod

vinod, working in keane india ltd as a flex developer

Updated on June 04, 2022

Comments

  • Vinod
    Vinod over 1 year

    How do you generate a random number within a given limit using the ActionScript? Suppose the limit is 1-100. Can you Answer me the explanation too

    I want to something put in the twitter or facebook, it wil just moves up n down (i.e moving the placing the object).. For that we need to generate the random numbers r8

  • alxx
    alxx almost 13 years
    one off? if Math.random() gives 1.0: 1.0 * (1 + 100 - 1) + 1 = 101.
  • Kel
    Kel almost 13 years
    No, I think it's correct. Math.random() generates a pseudo-random number n, where 0 <= n < 1. So it will never be 1.0, always a lower value that you floor afterwards anyway. From doc: livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/…