Hi,
I have looked in the existing posts to try to find the solution to
this, but cannot find an answer...
I want to be able to create a random number within a certain range,
that may be partially or entirely negative, i.e. between 17 and 25, -17
and 25, -25 and 25... etc.
I have found various solutions using Math and Random, which would work
if both limits are either positive or negative, or if they are the same
distance form the origin, ie. -25, 25... but nothing that will work for
all range possibilities.
Any help will be much appreciated!
Thanks,
Laura
Bart Cremers - 08 Feb 2006 12:01 GMT
public static int nextInt(int low, int high) {
if (low > high) {
int tmp = low;
low = high;
high = tmp;
}
int diff = high - low;
int i = rnd.nextInt(diff);
return i + low;
}
Boris Stumm - 09 Feb 2006 09:04 GMT
> public static int nextInt(int low, int high) {
> if (low > high) {
[quoted text clipped - 9 lines]
> return i + low;
> }
How about:
import static java.lang.Math.*;
public static int nextInt(int low, int high) {
return min(low, high) + rnd.nextInt(abs(high - low));
}
Roedy Green - 08 Feb 2006 17:53 GMT
>I want to be able to create a random number within a certain range,
>that may be partially or entirely negative, i.e. between 17 and 25, -17
>and 25, -25 and 25... etc
see http://mindprod.com/jgloss/pseudorandom.html#LOWHIGH

Signature
Canadian Mind Products, Roedy Green.
http://mindprod.com Java custom programming, consulting and coaching.