VOOZH about

URL: https://www.geeksforgeeks.org/dsa/generate-0-1-25-75-probability/

⇱ Generate 0 and 1 with 25% and 75% probability - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Generate 0 and 1 with 25% and 75% probability

Last Updated : 1 Jul, 2022

Given a function rand50() that returns 0 or 1 with equal probability, write a function that returns 1 with 75% probability and 0 with 25% probability using rand50() only. Minimize the number of calls to the rand50() method. Also, the use of any other library function and floating-point arithmetic are not allowed.

The idea is to use Bitwise OR. A bitwise OR takes two bits and returns 0 if both bits are 0, while otherwise, the result is 1. So it has 75% probability that it will return 1.

Below is the implementation of the above idea :


Output
11101010110101011010000101011110100010111110101111

Time Complexity: O(1)
Auxiliary Space: O(1)


On similar lines, we can also use Bitwise AND. Since it returns 0 with 75% probability, we have to invert the result.

// Random Function to that returns 1 with 75% 
// probability and 0 with 25% probability using
// Bitwise AND
bool rand75() 
{
 return !(rand50() & rand50());
}

Below is the implementation of the above idea :


Output
11111111000111101111110011111110011110111111010111

We can replace Bitwise OR and Bitwise AND operators with OR and AND operators as well - 

// Random Function to that returns 1 with 75%
// probability and 0 with 25% probability using 
// OR or AND operator
int rand75()
{
 return !(rand50() && rand50());
 // return rand50() || rand50()
}

We can also achieve the result using the left shift operator and Bitwise XOR


Output
10110100111011011110111100101111110111100001111111

Time Complexity: O(1)
Auxiliary Space: O(1)

Please note above solutions will produce different results every time we run them.
 

Comment
Article Tags:
Article Tags: