RandomNumBetween Or random_num

Non-platform specific questions.

RandomNumBetween Or random_num

Postby padilha007 » Thu Nov 25, 2010 4:32 am

I need one function to Generate a random integer from a to b

Ex:
random_num(a,b);
RandomNumBetween(a,b);
padilha007
 
Posts: 1
Joined: Thu Nov 25, 2010 4:30 am
Score: 0 Give a positive score

Re: RandomNumBetween Or random_num

Postby skydereign » Thu Nov 25, 2010 6:38 am

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);
}
User avatar
skydereign
 
Posts: 3510
Joined: Mon Jul 28, 2008 8:29 am
Score: 589 Give a positive score

Re: RandomNumBetween Or random_num

Postby Bee-Ant » Thu Nov 25, 2010 9:05 am

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... ;)
User avatar
Bee-Ant
 
Posts: 3723
Joined: Wed Apr 11, 2007 12:05 pm
Location: http://www.instagram.com/bee_ant
Score: 210 Give a positive score

Re: RandomNumBetween Or random_num

Postby BloodRedDragon » Fri Nov 26, 2010 1:13 am

Ah, Ive always wanted to know how to do this, thanks a bunch. :P
Current projects:
Techno-Tank Arena: on hold
Techno-Tank SuperPortal (working title): 0.1%
Bowels of Galaxies: 35% (was a bit too optimistic)
User avatar
BloodRedDragon
 
Posts: 123
Joined: Tue Jan 29, 2008 10:07 pm
Location: The Underworld
Score: 5 Give a positive score


Return to General

Who is online

Users browsing this forum: No registered users and 1 guest