sample solution

advertisement
Homework # 21 sample solution:
7-17.
Since a given number has 3 or 4 possible candidates except that # 1 and # 0
has none, we just need to construct all permutations with a given digit sequence and
possible candidates.
Assume that the input data is an array of numbers with each cell store a single digit
of the sequence.
construct_candidates(int input[], int k, int n, int c[], int *ncandidates){
char zero[1] ={‘ ’};
char one[1] ={‘ ’};
char two[3] ={‘A’,’B’,’C’};
char three[3] ={‘D’, ‘E’, ‘F’};
char four[3] ={‘G’, ‘H’, ‘I’};
char five[3] ={‘J’, ‘K’, ‘L’};
char six[3] ={‘M’, ‘N’, ‘O’};
char seven[4] ={‘P’,’Q’, ‘R’, ‘S’};
char eight[3] ={‘T’, ‘U’, ‘V’};
char nine[4] ={‘W’, ‘X’, ‘Y’, ‘Z’};
swith(input[k])
{
case 0 :
*ncandidates = 0;
break;
case 1 :
*ncandidates = 0;
break;
case 3 :
*ncandidates = 3;
c[*ncandidates] = three[3];
break;
…//the same thing for each of the remaining 7 cases;
…
}
}
Other functions are defined in the textbook.
7-18
We can represent each person by 1 bit of values: that is 0 if the person is
outside room and 1 if the person is inside. The problem now is how to generate all
2n combinations of n bits by modifying just one bit. We may do this by mathematical
induction:
Base case : n = 1, the possible combinations are 0, 1
n =2, the possible combinations are 00, 01, 11, 10
Induction hypothesis: Suppose we have 2n combinations of n bits, say x1,
x2, …, xm, where m = 2n, each xi is a distinct n-bit string and each pair of neighboring
xi and xi+1 differ by one bit (x1 and xm differ by one bit, too).
Inductive case: We show this is true also for n+1, that is, we could get 2n+1
combinations of (n+1) bits with the same property: We take two copies of x1, x2, …,
xm, where m = 2n, from the induction hypothesis. We append a `0’ to the end of xi in
the first set and append a `1’ to the end of xi in the other set, and arrange them as
follows:
x10, x20, …, xm0, xm1, …, x21, x11
then this sequence has 2n+1 distinct strings of (n+1) bits, such that each pair of
neighboring strings differ by one bit.
Using this sequence to guide people to move in and out of the room will meet
the requirement.
Download