int rand7()
{
int vals[5][5] = {
{ 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 = vals[i-1][j-1];
}
return result;
}
This solution solves the problem listed in details here.
The worst-case running time will be infinite if you keep on getting
i,jsuch thatvals[i-1][j-1] == 0, so thewhileloop will never terminate. This situation almost surely does not happen though.Let
Tdenotes the expected running time ofrand7(), we have the following observation:i == 1, 2, 3, 4, then no matter whatjis, we will havevals[i-1][j-1] != 0, so thewhileloop will iterate only once in this case; - This event occurs with probability 4/5i == 5andj == 1, thenvals[i-1][j-1] != 0and thewhileloop will iterate only once; - This event occurs with probability 1/25vals[i-1][j-1] == 0, so we need to start over with new random values(i, j). - This occurs happens with probability 4/25From the observation above, we have the following relationship:
Therefore the expected running time is
T = 25/21 = O(1).