I need to create a random number within two ranges, but I do not know how. Could someone help me?
Asked
Active
Viewed 346 times
-3
-
1rand(1,5) to generate 1->5, then a rand(1) to decide if should be in the 5-10 or 12-17 range... – Marc B Jul 03 '15 at 19:08
-
Do you mean the union of the two ranges? – Peter O. Jul 03 '15 at 19:13
-
possible duplicate of [Generating random integers in a range with Java](http://stackoverflow.com/questions/363681/generating-random-integers-in-a-range-with-java) – Henry Zhu Jul 03 '15 at 19:16
4 Answers
0
random numbers are generated between 0-1. let's make numbers<0.5 5-10 and numbers > 0.5 12-17 by simply multiplying them.

Alp
- 3,027
- 1
- 13
- 28
0
Try this :-
class PickRandomFromRange
{
private final List<Integer> range = new ArrayList<>();
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)
{
PickRandomFromRange rir = new PickRandomFromRange();
rir.addRange(5,10);
rir.addRange(12,17);
System.out.println(rir.getRandom());
}
}
The above code will basically just makes a list of all the numbers which are in the ranges you give it, then picks a random number from that list, which is therefore a random number from any of the ranges.

AnkeyNigam
- 2,810
- 4
- 15
- 23
0
I figured out a way, although, I don't know if it is an efficient way of solving my problem.
if(userInput == 4){
charNumber = 48+random.nextInt(76);
if(charNumber>47 && charNumber<58){
outputFile.print((char)charNumber);
counter++;
}
if(charNumber>64 && charNumber<91){
outputFile.print((char)charNumber);
counter++;
}
if(charNumber>90 && charNumber<97){
outputFile.print((char)charNumber);
counter++
}
if(charNumber>96 && charNumber<123){
outputFile.print((char)charNumber);
counter++;
}
}

Vishvak Seenichamy
- 102
- 10
0
The ranges 5-10 and 12-17 give you a total of 6 + 6 = 12 possible selections.
Pick a random number from 5 to 16. If the number is 11 or more then add one to it. Adding one effectively inserts the gap in your split range.
Random myRand = new Random();
// Number in range [5 .. 16].
int num = 5 + myRand.nextInt(17);
// Increase numbers beyond the gap.
if (num >= 11) {
num += 1;
}

rossum
- 15,344
- 1
- 24
- 38