rand7()
(0-6)+1 =(1-7)
Generate 0~6 from rand5()
rand2()
-> 1/2 probability to be 0
-> 1/2 probability to be 1
(0-1)+1 = (1-2)
rand7()
(0-6)+1 =(1-7)
(0,6) <= (1-21)%7=1,2,3,4,5,6,0,1,...21%7=0 = > 0~6
rand2() to generate 3 the probability is 3 since it should be as random as rand3()
rand3()
2. Implementation
public static int rand7()
{
while (true)
{
// 5* (0~4) + (0~4) = (0~20)+(0~4) = (0~24)
int num = 5*( rand5() -1 ) + ( rand5() -1 );
if ( num < 21 )
{
// ( 0~20 ) %7
// 0,1,2,3,4,5,6,0,1,2,3,4,5.....18%7=4,19%7=5,20%7=6
return (num%7+1);
}
}
}
3. Similar ones
No comments:
Post a Comment