VOOZH about

URL: https://www.geeksforgeeks.org/dsa/implement-rand12-using-rand6-in-one-line/

⇱ Implement rand12() using rand6() in one line - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Implement rand12() using rand6() in one line

Last Updated : 8 Jul, 2024

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 -

  • rand6() + !(rand6() % 2) * 6 or
  • rand6() + (rand6() & 1) * 6 or
  • rand6() + !(rand6() & 1) * 6

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);
}
  • rand6() * 2: This will return even numbers 2, 4, 6, 8, 10 and 12 with equal probability and
  • rand6() & 1: This will return 0 or 1 based on rand6() is even or odd respectively. So, the expression
  • (rand6() * 2) - (rand6() & 1): This will return random numbers from 1 to 12 with equal probability.

Below is the implementation of the above approach:


Output
Random number between 1 and 12: 7
Comment
Article Tags:
Article Tags: