Home > Mobile >  Java - Generate random number but exclude few ranges in between
Java - Generate random number but exclude few ranges in between

Time:09-07

I want to generate random number say between 1 to 100, but want to exclude ranges from 20 to 30 and 50-70.

CodePudding user response:

Random random = new Random();
final int AMOUNT_OF_RANGES = 3;
int num;
int range;

range = random.nextInt(AMOUNT_OF_RANGES)   1;
switch (range){
    case 1 -> num = random.nextInt(1, 21);
    case 2 -> num = random.nextInt(30, 51);
    case 3 -> num = random.nextInt(70, 101);
}

I took a range [1,20] and [30, 50] and [70, 100] as an example but actually u can add as many as u want. Make sure to add extra one to max digit to include it.Usually it works like [1, 20), so keep it in mind. Syntax is

random.nextInt(startOfRange, endOfRange);

CodePudding user response:

The ranges are not same so using a selector like r.nextInt(0,3) to decide which range to use would be inbalanced, in favour of the short ranges over bigger 70-100.

Instead use one range and adjust with if statement something like (not near a PC to test):

Random r = new Random(); 

int x = r.nextInt(1,69);
if ( x >= 39) 
    return x   32;
else if ( x >= 20)
    return x   11;
else return x;

This should handle 1..19, 31..49 and 71..100, but you may need to adjust if 30/70 are needed.

  •  Tags:  
  • java
  • Related