jeudi 29 novembre 2018

Generate random integer in range multiple of another integer in Java

I'm struggling to finish the utility method to generate a number in a range of 2 integers which is also a multiplier of another integer.

For example:

public static void main(String[] args) {
    getIntegerInRangeMultipleOf(100, 1000, 444);
} 

Should yield either 444 or 888. Nothing else.

I've came up with this solution:

public static int getIntegerInRangeMultipleOf(int minInclusive, int maxInclusive, int multiplier) {
    return Math.toIntExact(Math.round((Math.random() * (maxInclusive - minInclusive) + minInclusive) / multiplier) * multiplier);
}

But for the example above sometimes it yields 0 (zero) in addition to 444 and 888.

Please suggest how to fix the function.




Aucun commentaire:

Enregistrer un commentaire