Given a random generator random5(), the return value of random5() is 0 - 4 with equal probability. Use random5() to implement random7().

Solution: 先用random5()产生random25 : 5 * random5 + random5,再抛弃[21, 24),产生random21,再取% 7

  public int random7() {
    // you can use RandomFive.random5() for generating
    // 0 - 4 with equal probability.
    int random25 = 5 * RandomFive.random5() + RandomFive.random5();
    while (random25 > 20) {
      random25 = 5 * RandomFive.random5() + RandomFive.random5();
    }
    return random25 % 7;
  }

results matching ""

    No results matching ""