nichilus
nichilus

Reputation: 55

Generating random numbers that are twice as likely to put out even numbers

I'm wondering if there was a way to create a random number generator that generates a number between two integers, but is twice as likely to generate an even number than an odd number. At current, I haven't come up with a way that's even similar or close to 2x as likely.

Upvotes: 4

Views: 472

Answers (3)

Sash Sinha
Sash Sinha

Reputation: 22360

Implementing @SteveKuo 's suggestion in the comments:

import java.util.Scanner;

class Main {
  public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    System.out.print("Please enter the minimum number that can be generated: ");
    int min = scanner.nextInt();
    System.out.print("Please enter the maximum number that can be generated: ");
    int max = scanner.nextInt();
    int evenOrOdd = 0 + (int)(Math.random() * ((2 - 0) + 1));
    int random = 0;
    if(evenOrOdd == 2) { // generate random odd number
      if(max % 2 == 0) { --max; }
      if(min % 2 == 0) { ++min; }
      random = min + 2*(int)(Math.random() * ((max - min)/2+1));
    } else { //get random number between [(min+1)/2, max/2] and multiply by 2 to get random even number between min and max
      random = ((min+1)/2 + (int)(Math.random() * ((max/2 - (min+1)/2) + 1))) * 2;
    }
    System.out.printf("The generated random number is: %d", random);
  }
}

Try it here!

Upvotes: 0

John Bollinger
John Bollinger

Reputation: 180181

There are many ways you could do this. One would be to generate two integers: one between the user's bounds, and one between 0 and 2, inclusive. Replace the last bit of the first number with the last bit of the second number to get a result that is even twice as often as it is odd.

You do need to watch out for the possibility that the bit-twiddling last step puts the result out of bounds; in that event, you should re-draw from the beginning.

Upvotes: 1

NESPowerGlove
NESPowerGlove

Reputation: 5496

Simple but should work:

  • store random float call (0.0f - 1.0f) (random.nextFloat())
  • get a random integer in desired range
  • if random float call was less than 0.67f, if needed decrement or increment the random integer to make it even, return value
  • else, if needed decrement or increment the random integer to make it odd, return value

Make sure you decrement or increment towards the right direction if random integer is a boundary value of the desired range.

Upvotes: 4

Related Questions