Thursday, March 24, 2011

WAP To generate New random Function Using Another Given Random number function

You are given a random no. generator function rand04() that generates
random numbers between 0 and 4 (i.e., 0,1,2,3,4) with equal
probability. You have to design a random no. generator function
rand07() that generates numbers between 0 to 7 (0,1,2,3,4,5,6,7) using
rand04() such that rand07() generates all numbers between 0 to 7 with
equal probability.

import java.util.*;
class rand05
{

static int rand04()
{
Random r=new Random();
return (r.nextInt(5));
}

static int rand07()
{
int r;
do {
r = rand04() + 5 * rand04(); // 0 to 24.
} while (r >= 8 * 3);
return r / 3;

}



public static void main(String a[])
{
System.out.println(rand07());

}


}

Some Explanation

rand04() rand04() 5*rand04() Sum Sum/3
0 0 0 0 0
1 0 0 1 0
2 0 0 2 0
3 0 0 3 1
4 0 0 4 1
0 1 5 5 1
1 1 5 6 2
2 1 5 7 2
3 1 5 8 2
4 1 5 9 3
0 2 10 10 3
1 2 10 11 3
2 2 10 12 4
3 2 10 13 4
4 2 10 14 4
0 3 15 15 5
1 3 15 16 5
2 3 15 17 5
3 3 15 18 6
4 3 15 19 6
0 4 20 20 6
1 4 20 21 7
2 4 20 22 7
3 4 20 23 7
4 4 20 24 8

As you can see, each of the numbers from


Source & Great Info. http://www.ihas1337code.com/2010/11/rejection-sampling.html

No comments :