This is a pretty simple Java (though probably applicable to all programming) question:
Math.random()
returns a number between zero and one.
If I want to return an integer between zero and hundred, I would do:
(int) Math.floor(Math.random() * 101)
Between one and hundred, I would do:
(int) Math.ceil(Math.random() * 100)
But what if I wanted to get a number between three and five? Will it be like following statement:
(int) Math.random() * 5 + 3
I know about nextInt()
in java.lang.util.Random
. But I want to learn how to do this with Math.random()
.
int randomWithRange(int min, int max)
{
int range = (max - min) + 1;
return (int)(Math.random() * range) + min;
}
Output of randomWithRange(2, 5)
10 times:
5
2
3
3
2
4
4
4
5
4
The bounds are inclusive, ie [2,5], and min
must be less than max
in the above example.
EDIT: If someone was going to try and be stupid and reverse min
and max
, you could change the code to:
int randomWithRange(int min, int max)
{
int range = Math.abs(max - min) + 1;
return (int)(Math.random() * range) + (min <= max ? min : max);
}
EDIT2: For your question about double
s, it's just:
double randomWithRange(double min, double max)
{
double range = (max - min);
return (Math.random() * range) + min;
}
And again if you want to idiot-proof it it's just:
double randomWithRange(double min, double max)
{
double range = Math.abs(max - min);
return (Math.random() * range) + (min <= max ? min : max);
}