int rand7()
{
int x = 22;
while( x > 21)
x = rand5() + 5*rand5() - 5;
int r = 1 + (x % 7);
return r;
}
int rand7()
{
int x = 25;
while( x > 21)
x = rand5() + 5*rand5() - 5;
int r = (x >> 3) + (x & 7);
r = (r >= 7) ? r - 6 : r + 1;
return r;
}
A dice, when you throw gives only 1,2,.....21 (since you are rejecting 22,23,24,25 a.k.a rejection sampling theorem)
So total no. of possible are 21.
No. of ways getting "1"=3 (5*1+1-5,5*2+3-5,5*3+1-1)%7+1
No. of ways getting "2"=3 (5*1+1-5,5*2+3-5,5*3+1-1)%7+1
No. of ways getting "3"=3 (5*1+2-5,5*2+4-5,5*3+2-1)%7+1
and so on..
P(1)=3/21=1/7
P(2)=3/21=1/7 and so on...
Understand why these solutions are not right
http://www.geeksforgeeks.org/generate-integer-from-1-to-7-with-equal-probability/
x=foo()+foo()-1;
if (x !=8,9){
return x;
}
Now what's the probability here for p(1),p(2)...p(7)?
no. of ways of producing "1" =1 (1+1-1)
no. of ways of producing "2" =2 (2+1-1,1+2-1)
and so on...
Total no. of possible combination =5*5=25
P(1)=1/25;
P(2)=2/25
and so on...
So probabilities are not equal in this case !!
return (foo() + foo()%4 -1);
(foo()+foo()-1)%7+1
|
Also refer to http://www.geeksforgeeks.org/generate-integer-from-1-to-7-with-equal-probability/
Read full article from Random number 1..5 to 1..7
No comments:
Post a Comment