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 which produces either 0 or 1 each with 50% probability.


 
Below function generates 0 or 1 with 50% probability each, which we will be using 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

 

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 bitwise or logical OR operator. The idea remains similar. First make two calls to the random() function and then return negation of OR of results returned by the individual calls as shown below:

 

Download   Run Code

 

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

 
Thanks for reading.




Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂
 





Leave a Reply

Notify of
avatar
wpDiscuz