Moderate rand5()产生rand7() @CareerCup

1953人阅读 评论(2) 收藏 举报
分类:

参考这一文 http://hawstein.com/posts/19.10.html

比书上写得好



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()).

译文:

给你一个能生成1到5随机数的函数,用它写一个函数生成1到7的随机数。 (即,使用函数rand5()来实现函数rand7())。
 *
 */
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网站的观点或立场
    博客专栏
    个人资料
    • 访问:1224179次
    • 积分:16579
    • 等级:
    • 排名:第607名
    • 原创:407篇
    • 转载:64篇
    • 译文:0篇
    • 评论:291条