Adobe | Phone | Implement dice solution
Anonymous User
835

As many were asking solution for the below problem, I'm posting it here
Question - https://leetcode.com/discuss/interview-question/4405249/adobe-phone-implement-dice

Solution -

Intuition
The goal is to create a function that generates random numbers from 1 to 6 using a given toss() function that outputs binary values (0 or 1). To extend this, we're asked to generate random numbers from 0 to 7, which can be achieved by considering binary representations. However, we want to avoid the extremes (0 and 7) and, if encountered, recursively call the function until a suitable result is obtained. (See the image below)

Approach

  • Binary Representation
    Binary digits (0 or 1) are akin to the outcome of the toss() function.
    To generate a number from 0 to 7, we use three tosses to form a 3-bit binary number.

  • Convert Binary to Decimal
    Convert the binary result to a decimal number (base 10).

  • Handling Extremes (0 and 7)

    If the decimal result is 0 or 7, it's not suitable for our purpose.
    In such cases, we recursively call the function until a valid result between 1 and 6 is obtained.

image

Comments (0)