# Moderate rand5()产生rand7() @CareerCup

1953人阅读 评论(2)

package Moderate;

/**
*
* Write a method to generate a random number between 1 and 7, given a method that generates a random number between 1 and 5 (i.e., implement rand7() using rand5()).

*
*/
public class S17_11 {

public static int rand7() {
while (true) {
// 0,1,2,3,4 -> 0,5,10,15,20 -> evenly distributed in 0 - 24
int num = 5 * rand5() + rand5();
if (num < 21) {
return num % 7;
}
}
}

public static int rand5() {
return (int) (Math.random() * 100) % 5;
}

public static void main(String[] args) {
/* Test: call rand7 many times and inspect the results. */
int[] arr = new int[7];
int test_size = 1000000;
for (int k = 0; k < test_size; k++) {
arr[rand7()]++;
}

for (int i = 0; i < 7; i++) {
double percent = 100.0 * arr[i] / test_size;
System.out.println(i + " appeared " + percent + "% of the time.");
}
}
}


0
1

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
博客专栏
 CareerCup专栏 文章：41篇 阅读：59415
 LeetCode专栏 文章：148篇 阅读：563551
阅读排行
个人资料
• 访问：1224179次
• 积分：16579
• 等级：
• 排名：第607名
• 原创：407篇
• 转载：64篇
• 译文：0篇
• 评论：291条