![]() |
VOOZH | about |
Given a function, rand6() that returns random numbers from 1 to 6 with equal probability, implement the one-liner function rand12() using rand6() which returns random numbers from 1 to 12 with equal probability. The solution should minimize the number of calls to the rand6() method. Use of any other library function and floating point arithmetic are not allowed.
The idea is to use expression rand6() + (rand6() % 2) * 6. It returns random numbers from 1 to 12 with equal probability. The expression is equivalent to -
// if rand6() is even
if (rand6() % 2)
return 6 + rand6();
else // if rand6() is odd
return rand6();We can also use any one of the below expressions that works in a similar way -
Below is the implementation of the above approach:
Output:
100237 100202 99678 99867 100253 99929 100287 100449 99827 99298 100019 99954
Another Solution:
int rand12()
{
return (rand6() * 2) - (rand6() & 1);
}Below is the implementation of the above approach:
Random number between 1 and 12: 7