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

Solution: 每次call random5 5次,产生[0, 5^5 - 1 = 3124],若>= 3000,重新产生,否则返回% 1000

  public int random1000() {
    // you can use RandomFive.random5() for generating
    // 0 - 4 with equal probability.
    int rand = random5power5();
    while (rand >= 3000) {
      rand = random5power5();
    }
    return rand % 1000;
  }
  private int random5power5() {
    int ans = 0;
    for (int i = 0; i < 5; i++) {
      ans = ans * 5 + RandomFive.random5();
    }
    return ans;
  }

results matching ""

    No results matching ""