Home > Mobile >  How to get two random numbers with the same limit
How to get two random numbers with the same limit

Time:11-21

I want to get two random numbers or variables respectively within the same range, taking into account that the sum of the two numbers does not exceed the limit imposed by Math.random(). How can I do that?

For example there are three million snowflakes that land randomly either on the roof or on the ground

CodePudding user response:

There are a few distinct ways to go about this, but the easiest is to pick one random number up to the limit, and then set the second number to be the difference between that and the limit. Something like:

import java.util.Random;
public class Main {
    public static void main(String args[]) {
      Random random = new Random();
      int limit = 1000000;
      int ground = random.nextInt(limit);
      int roof = limit - ground;
      System.out.printf("%s, %s", roof, ground);
    }
}

If you don't want the sum to be exactly the limit every time, you could either first set the limit to be random in some range, or have the second be a random number up to the difference. There are a lot of options that will result in a lot of different distributions.

CodePudding user response:

Maybe take the average? (number1 number2...) / amount of numbers

  • Related