getting 2 random numbers to add up to less than number n

104 Views Asked by At

So i'm trying to code a game for context. I'd like to be able to get 2 random numbers(a, b) that will add up to less then number n.

Here's my initial approach.

I get a random number between 0 and n.

Lets says n = 100 in an example. And my first random number is 78.

so i would take the remainder, in this case 22 and find a random number between 0 and 22. And then it would spit out some random number.

I can't seem to think of an approach where the second number gets as much "randomness" opportunity as the first number, due to the range being reduced.

What are some more approaches to getting 2 random numbers that must be less then sum n?

2

There are 2 best solutions below

1
On BEST ANSWER

This method selects two random nonnegative integers $a$ and $b$ so that $a+b< n$. This method is perfect in the sense that every possible ordered pair $(a,b)$ is equally likely. This means that $a$ and $b$ will have the exact same degree of randomness.

  • Choose an integer $x$ randomly in the range $1$ to $n+1$.

  • Choose an integer $y$ randomly in the range $1$ to $n$.

    • If $y\ge x$, replace $y$ with $y+1$.
  • Let $a=\min(x,y)-1$, and let $b=\max(x,y)-\min(x,y)-1$.

3
On

We might as well take $n=1$. You can multiply the numbers that come from this by $n$ to get the range you want.

You are trying to sample the triangle $a \ge 0, b \ge 0, a+b \le 1$ uniformly. This triangle is half of the square $0 \le a \le 1, 0 \le b \le 1$, which is easy to sample-just draw $a$ and $b$ uniformly from $[0,1]$. Now if $a+b \gt 1$, we can fold over the diagonal. Instead of $a,b$, use $1-a,1-b$ for your variables. The sum is $2-a-b$, which is less than $1$ because $a+b \gt 1$.

$a$ and $b$ have the same distribution, which is a triangle with density $2$ at $0$ falling linearly to $0$ at $1$.