10

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?

Tim B
  • 40,716
  • 16
  • 83
  • 128
m0a
  • 1,005
  • 2
  • 15
  • 29
  • 5
    Simple: generate a random number over half the range, and then multiply by 2. – Jesper Nov 23 '15 at 12:10
  • Oh! Clever. =) I think that should work. Thanks! – m0a Nov 23 '15 at 12:11
  • @Jesper but then the first quarter even numbers in the range cannot be generated. – rajuGT Nov 23 '15 at 12:12
  • @rajuGT What do you mean? All 3 answers look valid to me. – Tim B Nov 23 '15 at 12:15
  • Given range is from 2 to 100. Proposed solution is generate a random number over half the range. i.e. 2 to 49. in this the lowest possible value can be 2. then multiply it by 2. i.e. 4. So here, we cannot generate random number 2 here. Let me know if my understanding is not correct or inline with you all. (also considering the random range ), sorry that should not be first quarter in my earlier comment. – rajuGT Nov 23 '15 at 12:20

8 Answers8

15

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.

Tim B
  • 40,716
  • 16
  • 83
  • 128
3

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
}
SomeJavaGuy
  • 7,307
  • 2
  • 21
  • 33
3

In Java 1.7 or later, I would use ThreadLocalRandom:

import java.util.concurrent.ThreadLocalRandom;

// Get even random number within range [min, max]
// Start with an even minimum and add random even number from the remaining range
public static int randEvenInt(int min, int max) {
    if (min % 2 != 0) ++min;
    return min + 2*ThreadLocalRandom.current().nextInt((max-min)/2+1);
}

// Get odd random number within range [min, max]
// Start with an odd minimum and add random even number from the remaining range
public static int randOddInt(int min, int max) {
    if (min % 2 == 0) ++min;
    return min + 2*ThreadLocalRandom.current().nextInt((max-min)/2+1);
}

The reason to use ThreadLocalRandom is explained here. Also note, that the reason we +1 to the input to ThreadLocalRandom.nextInt() is to make sure the max is included in the range.

Community
  • 1
  • 1
rouble
  • 16,364
  • 16
  • 107
  • 102
1

After you get the random number between 1 and 100 and multiply it by 2, you can get the number % 100. Something like:

int random = rand.nextInt(100);
random = (random * 2) % 100;

This way number will always be less than 100 and even.

Konstantin Yovkov
  • 62,134
  • 8
  • 100
  • 147
1

Another approach (maybe not the optimal one):

  1. Create an array (or a List) with all the even numbers between 1 and 100. (This is easy with a loop)
  2. When you need a random even number just take a random number from that array or list (using random with length or size).
Averroes
  • 4,168
  • 6
  • 50
  • 63
  • 2
    That's horribly inefficient. The only way you could justify this is if there was some complicated maths to work out eligible numbers (for example primes only) or if you wanted to make sure no numbers were repeated (by removing them ) – Tim B Nov 23 '15 at 12:30
  • @TimB I agree that is not the most efficient one and it would not be my choose (yours is more clear and elegant) but as I have tested it seems it's not so inneficient. Provide that the List is already initialized your code takes ~14 ms in generating 1000000 numbers and my code takes ~15 ms (in my machine). – Averroes Nov 23 '15 at 13:01
  • 1
    It's not a terrible solution - it will work and in some cases is the only way (as noted in my first comment). However as you said yourself provided the list is initialized, which means always selecting from the same range. There are also memory performance hits and more cache time being lost, and the cost becomes worse the larger the range. Basically it's a solution with poor scaling. – Tim B Nov 23 '15 at 13:03
1

Best way to generate even random number between 2 and 1000

Random random = new Random();
        int Low = 2;
        int High = 1000;
        int randomNumber = random.nextInt(High-Low) + Low;
        if(randomNumber % 2 != 0){
            randomNumber = randomNumber + 1;
        }

https://www.google.com/search?q=sim+phone+details

1
private int getRandomNoOdd(int maxValue) {//min value is 0, including zero, max value can potentially be reached by randomness
    int random = 0;
    while (true) {
        random = (int) (Math.random() * (maxValue + 1));
        if (random % 2 != 0)
            continue;
        break;
    }
    return random;
}
1

You can also get a random number from a range then, if % 2 != 0, add 1.

R. drt
  • 26
  • 4