You would simply calculate the difference between min and max
example -30 and 30
to get:
delta <-- absolute value of (30 - (-30))
then find a random number between 0 and delta.
There is a post related to this already.
afterwards translate the number along the number-line by your constant min.
If using the Random class:
1) is added to the equation here for Random.nextInt(someInt) because nextInt returns:
someVal < someInt so you need to be sure to include the boundaries in the functions output.
Something about this code is makes me cautious:
return min +
(int)(Math.random() * (max - min + 1));
}
When casting rounding doubles to cast to ints:
int someRandomDoubleRoundedToInteger = (int)(someDouble + 0.5)
Does it work? This is for my benefit, maybe some other newbies will be amused, or maybe I made a blunder so:
lets choose 1 and 10 to begin with.
Pick a number between 1 and 10 (Inclusive) I pick 10
Math.Random Excludes 0 and 1. so 0.9999999999999999 * (10 - 1 + 1) = 9.999999999999999 cast to int, so lob off everything after the decimal produces 9 the we add 1 to 9 to return 10. (using random anything from (.9 to .999999999999) also will produce 10
I want to choose 1 from between 1 and 10.
In this case the random method puts out it's closest value to zero say:
0.00000000000000001 * (10 - 1 + 1) cast to int is zero 0 We return 1+0. So that works.
Huh, seems to work. Looks like a very, very, very minor bias against 1 since we are never including "0" as a possibility but it should be acceptable.
The method works, If the random generator evenly covers the entire area between 0 and 1.
How many different numbers can be represented between the {0,1} interval, are they evenly spaced?
I think it works.