christian.vogel - 4 months ago 6

Java Question

I need to write a short randomizer which generates a random number between 1 to N where the random number is increasing by multiples of M.

For example: generate numbers between 1 and (N=30) increasing by multiples of (M=5). The only possible generated numbers can be then: 1,5,10,15,20,25 and 30. Hope you get what I mean :)

Normally if you use

`new Random().nextInt(30)+1`

Any help, links, or directions are very appreciated?

That the sequence of generated random numbers could include 1 not zero is one of the requirements of the method. Precisely, the sequence always starts with the lower bound (min). In the example the lower bound is 1 and therefore there can't be zero in the sequence. It's odd I know, but those are the requirements I have to follow ;)

Answer

You could multiply the random value by 5. Since you want to have 1 instead of 0 just look for that value and alter it specifically:

```
static final Random random = new Random(System.currentTimeMillis());
public int random(int range, int multiple) {
int value = random.nextInt(range / multiple) * multiple;
return value == 0 ? 1 : value;
}
```

Source (Stackoverflow)

Comments