# Generate Desired Random Numbers With Equal Probability

Write an algorithm to generate random numbers from 1 to 12 with equal probability using a given function which generates random numbers from 1 to 6 with equal probability.

The idea is to make two separate calls to the specified function and store the result in two variables, say x and y, which would be random numbers between 1 to 6. Then we can easily establish that –

1. The expression `2*x` returns an even random number between 2 to 12 (i.e. 2, 4, 6, 8, 10 and 12) with equal probability.

2. The expression `(y & 1)` returns either 0 or 1 depending upon whether y is even or odd.

The idea is to use the the expression `(x * 2) – (y & 1)` will return random numbers from 1 to 12 with equal probability. This works since

1. if `(y & 1)` is 0, the expression returns the random even numbers 2, 4, 6, 8, 10, and 12 with equal probability.

2. if `(y & 1)` is 1, the expression returns the random odd numbers 1, 3, 5, 7, 9, and 11 with equal probability.

Output:

1 ~ 8.33%
2 ~ 8.35%
3 ~ 8.35%
4 ~ 8.31%
5 ~ 8.32%
6 ~ 8.33%
7 ~ 8.29%
8 ~ 8.38%
9 ~ 8.35%
10 ~ 8.34%
11 ~ 8.35%
12 ~ 8.31%

Another way to generate the desired random numbers can be done using the expression
`x + (y & 1)*6` or `x + !(y & 1)*6` where x and y represents output of two distinct calls made to the `random()` function.

##### How this works?

Let’s consider the `x + (y & 1)*6` expression:

1. `x` returns random numbers from 1 to 6 with equal probability.

2. `(y & 1)` returns 0 or 1 depending upon whether y is even or odd.

Now if y is even, the expression reduces to x, which gives random numbers from 1 to 6 and if y is odd, the expression is reduced to `(x + 6)`, which gives random numbers from 7 to 12.

Output:

1 ~ 8.29%
2 ~ 8.35%
3 ~ 8.34%
4 ~ 8.39%
5 ~ 8.29%
6 ~ 8.32%
7 ~ 8.31%
8 ~ 8.32%
9 ~ 8.36%
10 ~ 8.34%
11 ~ 8.32%
12 ~ 8.37%

(1 votes, average: 5.00 out of 5)