I understand how to make a random number which is between two numbers:
1 + (int)(Math.random() * ((10 - 1) + 1))
or
min + (int)(Math.random() * ((max - min) + 1))
But how do I go about generating a random number which falls into multiple ranges?
For example: number can be between 1 to 10 or between 50 to 60
I'd go with something like this, to allow you to do it with as many ranges as you like:
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
class RandomInRanges
{
private final List<Integer> range = new ArrayList<>();
RandomInRanges(int min, int max)
{
this.addRange(min, max);
}
final void addRange(int min, int max)
{
for(int i = min; i <= max; i++)
{
this.range.add(i);
}
}
int getRandom()
{
return this.range.get(new Random().nextInt(this.range.size()));
}
public static void main(String[] args)
{
RandomInRanges rir = new RandomInRanges(1, 10);
rir.addRange(50, 60);
System.out.println(rir.getRandom());
}
}
First generate an integer between 1 and 20. Then if the value is above 10, map to the second interval.
Random random = new Random();
for (int i=0;i<100;i++) {
int r = 1 + random.nextInt(60-50+10-1);
if (r>10) r+=(50-10);
System.out.println(r);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With