Random number generation

Implement a method rand7() given rand5(). That is, given a method that generates a random number between 0 and 4(inclusive), write a method that generates a random number between 0 and 6(inclusive).

C++:
01 int rand7()
02 {
03     int t=0;
04     int p=1;
05     for(int i=0;i<3;i++){
06         while(true){
07             if(rand5()<2)
08                 break;
09             else if(rand5()>2){
10                 t=t+p;
11                 break;
12             }
13         }
14         p=p*2;
15     }
16     if(t!=7)
17         return t;
18     else
19         return rand7();
20 }
Advertisements
This entry was posted in Probability. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s