Generating a random number between multiple ranges
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);
}
First, you need to know how many numbers are in each range. (I'm assuming you are choosing integers from a discrete range, not real values from a continuous range.) In your example, there are 10 integers in the first range, and 11 in the second. This means that 10/21 times, you should choose from the first range, and 11/21 times choose from the second. In pseudo-code
x = random(1,21)
if x in 1..10
return random(1,10)
else
return random(50,60)