Skip to content
Advertisement

How to get a random multiple of a given number within a range

I’m making a program in which a JPanel is created with a random RGB value and the user has to use buttons to match the color in another JPanel.

I want the random R, G, and B values to be multiples of 15, though, so the user can match the color more easily.

Right now my code looks like this:

int randRed = rand.nextInt(255);

and the same for green and blue. I could use a modulus to repeat the code until it happens to be a multiple of 15 but that would be terribly inefficient.

What is the best method to achieve a random multiple of 15 less than 255?

Advertisement

Answer

RIght after posting I figured it out…

int randRed = (rand.nextInt(17)+1)*15;

15 goes into 255 17 times, so just multiple a random int between 0 and 17, add 1, and multiply by 15.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement