Forum

random() in N increments?

Discuss programming in the QuakeC language.

Moderator: InsideQC Admins

random() in N increments?

Postby Orion » Fri Nov 27, 2009 3:22 pm

Hi, is there a way to for example return a random number between 5 and 15 in 5 point increments?

Any help appreciated. :)


EDIT: Is that form right?

Code: Select all
float(float min, float max, float inc) incrandom =
{
   local float i, j;
   
   j = ceil(random()*max);
   if (j < min)
      return min;
   
   i = min;
   while (i < j)
   {
      i = i + inc;
   }
   
   return i;
};
User avatar
Orion
 
Posts: 476
Joined: Fri Jan 12, 2007 6:32 pm
Location: Brazil

Postby Downsider » Fri Nov 27, 2009 7:47 pm

Why don't you just get an integer between 0 - 2 and mutiply it by 5, then add 5?
User avatar
Downsider
 
Posts: 621
Joined: Tue Sep 16, 2008 1:35 am

Postby Wazat » Fri Nov 27, 2009 7:55 pm

Uncompiled and untested code below. If it isn't completely right it will hopefully help you anyway. :)

Code: Select all
float(float min, float max, float inc) incrandom =
{
  float range;
  range = (max - min) / inc;

  range = rint(range * random());
  return min + range*inc;
}


Assuming min and max are both increments of inc, this will give you what you want. It's up to the user to pass in valid data. You could add some code to the top of the function to ensure inc divides evenly, if you have a modulus function. Or just trust that min and max really are what the user wants. :)
When my computer inevitably explodes and kills me, my cat inherits everything I own. He may be the only one capable of continuing my work.
Wazat
 
Posts: 771
Joined: Fri Oct 15, 2004 9:50 pm
Location: Middle 'o the desert, USA


Return to QuakeC Programming

Who is online

Users browsing this forum: No registered users and 1 guest