Moderate rand5()产生rand7() @CareerCup

参考这一文 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.");
		}
	}
}


你可能感兴趣的:(Moderate rand5()产生rand7() @CareerCup)