All Downloads are FREE. Search and download functionalities are using the official Maven repository.

g0401_0500.s0470_implement_rand10_using_rand7.Solution Maven / Gradle / Ivy

There is a newer version: 1.38
Show newest version
package g0401_0500.s0470_implement_rand10_using_rand7;

// #Medium #Math #Randomized #Probability_and_Statistics #Rejection_Sampling
// #2022_07_19_Time_8_ms_(82.15%)_Space_50.7_MB_(31.69%)

import java.util.Random;

/**
 * 470 - Implement Rand10() Using Rand7()\.
 *
 * Medium
 *
 * Given the **API** `rand7()` that generates a uniform random integer in the range `[1, 7]`, write a function `rand10()` that generates a uniform random integer in the range `[1, 10]`. You can only call the API `rand7()`, and you shouldn't call any other API. Please **do not** use a language's built-in random API.
 *
 * Each test case will have one **internal** argument `n`, the number of times that your implemented function `rand10()` will be called while testing. Note that this is **not an argument** passed to `rand10()`.
 *
 * **Example 1:**
 *
 * **Input:** n = 1
 *
 * **Output:** [2]
 *
 * **Example 2:**
 *
 * **Input:** n = 2
 *
 * **Output:** [2,8]
 *
 * **Example 3:**
 *
 * **Input:** n = 3
 *
 * **Output:** [3,8,10]
 *
 * **Constraints:**
 *
 * *   1 <= n <= 105
 *
 * **Follow up:**
 *
 * *   What is the [expected value](https://en.wikipedia.org/wiki/Expected_value) for the number of calls to `rand7()` function?
 * *   Could you minimize the number of calls to `rand7()`?
**/
@SuppressWarnings("java:S2245")
public class Solution {
    private final Random random = new Random();

    public int rand10() {
        int x = rand7();
        int y = rand7();
        int value = (x - 1) * 7 + y;
        if (value >= 41) {
            return rand10();
        }
        return value % 10 + 1;
    }

    private int rand7() {
        return random.nextInt(7) + 1;
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy