You have a method that generates random numbers between 1 to 5 with same probability. Using this method, how would you define another method to generate a random number between 1 to 7 with equal probability ?
7 -Ans- Suppose we have a 2D array of integers like this:
int[][] numArray = {
1,2,3,4,5,
6,7,1,2,3,
4,5,6,7,1,
2,3,4,5,6,
7,0,0,0,0
}
Now, this 2D array has total 25 numbers (21 non zero numbers and 4 zeroes).
All the 21 non-zero numbers belong to the range 1-7 (there are 3 occurrences each for 1,2,3,...7 ).
Thus, the individual probability of selecting any non-zero number randomly is same for all 1,2,3,...7.
Even, while trying to select a non-zero number if we select a zero, and then proceed with more trials to select a non-zero, then also the individual probability remains the same for all the non-zero numbers.
Now, suppose rand5() is the function that returns a random number in the range 1-5.
Hence keeping an eye on the logic discussed above the desired function would look like:
int rand7() {
int[][] numArray = {
1,2,3,4,5,
6,7,1,2,3,
4,5,6,7,1,
2,3,4,5,6,
7,0,0,0,0
}
int result = 0;
while (result == 0) {
int i = rand5();
int j = rand5();
result = numArray[i - 1][j - 1];
}
return result;
}