![]() |
VOOZH | about |
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 :
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 :
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 -
10110100111011011110111100101111110111100001111111
Time Complexity: O(1)
Auxiliary Space: O(1)
Please note above solutions will produce different results every time we run them.