Generate 0 and 1 with 75% and 25% probability
Write an algorithm to generate 0 and 1 with 75% and 25% probability, respectively, using a specified function that produces either 0 or 1 each with 50% probability.
The following function generates 0 or 1 with 50% probability each, which can be used to generate 0 and 1 with 75% and 25% probability:
1 2 3 4 5 6 7 8 |
int random() { // `rand()` produces a random number int random = rand(); // if the random number is even, return 0; otherwise, return 1 return (random % 2); } |
1. Using Bitwise AND Operator (or Logical AND Operator)
We can use bitwise or logical AND
operator to solve this problem. The idea is two make two calls to the random()
function and return AND
of results returned by the individual calls.
1 2 3 4 5 6 7 8 9 |
// Return 0 and 1 with 75% and 25% probability, respectively, using the // specified function and bitwise AND operator int generate() { int x = random(); int y = random(); return (x & y); } |
Explanation:
y can be either {0, 1}
(x & y) can be either {0, 0, 0, 1}
2. Using Bitwise OR Operator (or Logical OR Operator)
We can also use a bitwise or logical OR
operator. The idea remains similar. First, make two calls to the random()
function and then return the negation of OR
of results returned by the individual calls, as shown below:
1 2 3 4 5 6 7 8 9 |
// Return 0 and 1 with 75% and 25% probability, respectively, using the // specified function and bitwise OR operator int generate() { int x = random(); int y = random(); return !(x | y); } |
Explanation:
y can be either {0, 1}
(x | y) can be either {1, 1, 1, 0}
!(x | y) can be either {0, 0, 0, 1}
3. Using Left Shift Operator and Bitwise XOR Operator
The idea is to use this expression: (random() << 1) ^ random()
.
How this works?
(random() << 1) can be either 0000 or 0010
(random() << 1) ^ random() can be either {0001, 0011, 0000, 0010}
1 2 3 4 5 |
// Return 0 and 1 with 75% and 25% probability, respectively, using the // specified function, left shift operator, and bitwise XOR operator int generate() { return ((random() << 1) ^ random()) == 0; } |
Author: Aditya Goel
Generate numbers from 1 to 7 with equal probability using a specified function
Return 0, 1, and 2 with equal probability using a specified function
Get 0 and 1 with equal probability using a specified function
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)