Thursday, September 29, 2011

[Java] Generate random numbers in a range

I knew the method I've been using to generate random numbers in a range was very inefficient as it would be doing unnecessary calculations an extra several hundred times per second; causing the UI of my games to become choppy. The only problem was, I wasn't sure of a better way to do it...

I was doing something along the lines of:

int low;
int high;
int temp = random(high);
while (temp < low) temp = random(high);
return temp;

Yes, that did get the job done, but as I mentioned, it was doing WAY more calculations than it should have been.

There must be a simpler way...

Then it hit me...


public int getRandom(int low, int high){
return (int)(low + (random.nextInt(high - low)));
}

In 1 call, as opposed to the many that could potentially have been done before, the above code produces a number within range.

It creates a random number based on the difference between the high/low, and then adds the random value to the minimum in the range.

So far this is the most efficient way I've found to generate random numbers in a range and has saved me a lot of unnecessary computations; making the games look much crisper.

Thank you math.

No comments:

Post a Comment