Page 1 of 1

RandomNumBetween Or random_num

PostPosted: Thu Nov 25, 2010 4:32 am
by padilha007
I need one function to Generate a random integer from a to b

Ex:
random_num(a,b);
RandomNumBetween(a,b);

Re: RandomNumBetween Or random_num

PostPosted: Thu Nov 25, 2010 6:38 am
by skydereign
Stick this in global code. Essentially it finds the maximum difference in the random numbers, and uses the normal rand. That way you get a rand within the proper range when added to the low.

Code: Select all
int
random_num (int low, int high)
{
    random = rand(high-low);
    return(low+random);
}

Re: RandomNumBetween Or random_num

PostPosted: Thu Nov 25, 2010 9:05 am
by Bee-Ant
Code: Select all
int RandomBetween(int a,int b)
{
    int random=rand(max(a,b)-min(a,b));
    int start=min(a,b);
    return start+random;
}


With this code :
SomeNum = RandomBetween(-46, 89);
and
SomeNum = RandomBetween(89,-46);

Will be the same... ;)

Re: RandomNumBetween Or random_num

PostPosted: Fri Nov 26, 2010 1:13 am
by BloodRedDragon
Ah, Ive always wanted to know how to do this, thanks a bunch. :P