Generating random numbers that are twice as likely to expose even numbers

I am 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 present, I have not come up with a method that is even similar or close to 2x, most likely.

+4
source share
3 answers

Simple but should work:

  • store random float call ( 0.0f- 1.0f) ( random.nextFloat())
  • get a random integer in the required range
  • if the random float call was less 0.67f, if it is necessary to decrease or increase the random integer to make it even, the return value
  • else, , ,

, , .

+4

. : 0 2 . , , , .

, - ; .

+1

@SteveKuo :

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);
  }
}

!

0

Source: https://habr.com/ru/post/1671393/


All Articles