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.

Practice this problem

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. 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.

Download  Run Code

 
Explanation:

x can be either {0, 1}
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:

Download  Run Code

 
Explanation:

x can be either {0, 1}
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() returns either 0000 or 0001 (in binary)
(random() << 1) can be either 0000 or 0010
(random() << 1) ^ random() can be either {0001, 0011, 0000, 0010}

Download  Run Code

 
Author: Aditya Goel