Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate a random even number inside a range?

Tags:

java

random

range

Here's the format I'm following:

 int randomNum = rand.nextInt((max - min) + 1) + min;

So here's my code. I'm trying to get a random even number between 1 and 100:

 Random rand = new Random(); 
 int randomNum = rand.nextInt((100 - 2) + 1) + 2;

I saw one solution is to multiply the number by 2, but that breaches the intended range.

I thought of doing a bunch of if statements to solve this, but it seems overly complex. Is there a relatively simple solution?

like image 344
m0a Avatar asked Nov 23 '15 12:11

m0a


People also ask

How do I make an even number in Excel?

Select a blank cell, and type this formula =EVEN(RANDBETWEEN(X,Y)) (X and Y indicate any integer numbers, and X<Y), for instance, I want to randomize even numbers between -5 and 10, now I type =EVEN(RANDBETWEEN(-5,10)) into an empty cell, press Enter key, if you need, you can drag the fill handle to a range with this ...

How do you do a random double range?

In order to generate Random double type numbers in Java, we use the nextDouble() method of the java. util. Random class. This returns the next random double value between 0.0 (inclusive) and 1.0 (exclusive) from the random generator sequence.


2 Answers

Just generate a number from 0 to 49 and then multiply it by 2.

Random rand = new Random(); 
int randomNum = rand.nextInt(100/2) *2;

To do it in a range just add the range in:

int randomNum = startOfRange+rand.nextInt((endOfRange-startOfRange)/2) *2;

Note that startOfRange should be an even number or converted into an even number.

like image 108
Tim B Avatar answered Oct 05 '22 13:10

Tim B


Here´s a tiny example on how to do it

static Random rand = new Random();

public static void main(String[] args) {
    for(int i = 0;i<100;++i)
        System.out.println(generateEvenNumber(0, 100));

}

private static int generateEvenNumber(int min, int max) {
    min = min % 2 == 1 ? min + 1 : min; // If min is odd, add one to make sure the integer division can´t create a number smaller min;
    max = max % 2 == 1 ? max - 1 : max; // If max is odd, subtract one to make sure the integer division can´t create a number greater max;
    int randomNum = ((rand.nextInt((max-min))+min)+1)/2; // Divide both by 2 to ensure the range
    return randomNum *2; // multiply by 2 to make the number even
}
like image 27
SomeJavaGuy Avatar answered Oct 05 '22 14:10

SomeJavaGuy