I suppose what you mean is given a random number generator that generates 1-
5 with equal prob. (1/5), create another random generator that generates 1-7
with equal prob (1/7).
Assuming the 1-5 generator generates i.i.d. numbers. We will put two numbers
in one group, e.g. from
1, 2, 5, 3, 1, 4, ...
we get
(1, 2), (5, 3), (1, 4), ...
We will have 25 different pairs with equal prob (1/25). We only pick 14
pairs as valid pairs, discard other 11 pairs. We call them pair #1, #2, ...,
#14. When we get pair #1or #2, we output number 1, ... if we get pair #13
or #14, we output 7.
基本方法就是产生一串序列
1,4,5,3,2,4
然后前后两两划分为一组,比如(1,4),(5,3),因为总共有5X5 =25种等概率的可能,不能被7整除,可以拿掉4种,这样剩下21种,编号为#1,#2,...#21
如果出现#1,#2,#3则输出1,....如果出现#19,#20,#21则输出7,如果出现了被拿掉的那4种情况则忽略之
第二种方法:
算法思路是:
1. 通过 rand5()*5+rand5() 产生 6 7 8 9 10 11 …… 26,27 28 29 30 这25个数,每个数的出现机率相等
2. 只需要前面 3*7 个数,所以舍弃后面的4个数
3. 将 6 7 8 转化为 1,9 10 11 转化为 2,……,24 25 26 转化为 7。公式是 (a-3)/3
int rand7()
{
int a;
while( (a=rand5()*5+rand5()) > 26 );
return (a-3)/3;
}
复制代码
或者
int rand7()
{
int sum = 0;
for(int i=0; i<7; i++)
{
sum += ( rand5() - 1 ) * pow(5,i) ;
}
return (sum%7+1);
}