算法导论上有一题和这题很相似:已知random等概率返回0或者1,那么试写一个函数等概率返回[a,b]之间的整数。思路就是2进制表示[0, b-a]之间的数,先计算出至少需要多少位,按位生成一个二进制数,一旦大于b-a就重新生成。
我同样先写一个rand2()返回二进制,然后再写rand7(),利用统计的方法验证该方法是否正确:
package 实际问题; public class Random5to7 { /** * 已知函数rand5()可以产生[1, 5]之间的随机数,请编写函数rand7() 注:不可以使用Random函数 */ public static void main(String[] args) { int test[] = new int[8]; for(int i=1; i<=7; i++) test[i]=0; for(int i=0; i<21000; i++) { test[rand7()] ++; } for(int i=1; i<=7; i++) System.out.println(i+":" + test[i]); } /* 已知函数 */ static int rand5() { return (int)(Math.random()*5) + 1; } static int rand7() { //7 使用3个bit就可以进行标示 int res = 8; while( res == 8) { res = 0; for(int i=0; i<3; i++) res += rand2()*Math.pow(2, i); } return res; } static int rand2() { int i = rand5(); while( i== 5) i = rand5(); return (i & 1); } }
查看统计结果还是比较符合条件的