I want to generate a random Integer that is:
- Inside the range [Min, Max]
inclusive
- The range can be [5,20], [-29, -3] or [-13, 13] (It can be in any range, positive or negative or in between)
- The code is working fine in Android
What I got so far is this, but it seems not working with negative ranges !
1 + (int)(Math.random() * ((Max - Min) + 1));
Try this
I'm pretty sure you want
However, I should point out that the range [-3,-29] has its min and max reversed. (And the same with [5,-13] as was pointed out by Merlyn.)
If you want to just put in any two numbers for the range, a and b then use the code
That way you won't have to worry about the order. This will even work for a==b.
If the caller can guarantee that
bound1
will be less or equal tobound2
than you can skip the step of figuring out the minimum and maximum bounds; e.g.I haven't tested this on Android, but it should work on any Java or Java-like platform that supports those methods in conformance to the standard (Sun) Java SE specifications.
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:
When casting rounding doubles to cast to ints:
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.
Has anyone mentioned that his min and max are reversed? Because that's what is screwing up his code.
EDIT
The other thing that's messing up his code: it should be
Min +
not1 +