PARTIAL ANSWERS | |||||
CS3343, Spring 2012, Final Exam, 7 Apr 2012 | |||||
Index | Key | Hash addr |
---|---|---|
4 | ||
5 | hortense | 7 |
6 | hamish | 9 |
7 | wayne | 8 |
8 | ralph | 8 |
9 | roger | 10 |
10 | henry | 10 |
11 |
int m = 50; // size of hash table public int hash(String s, int p, int m) { return (s.charAt(0) + s.charAt(s.length()-1))%m; } |
|
|
![]() |
|
|
|
Original tape looks like: L = left segment of 1's, M = middle segment of 0's, R = right segment of 1's All 0's outside these segments, indefinitely far. <--L--><--M--><--R--> ...00011...1100...0011...1100... OK, here is what the program is doing: 1. Print 0 at left end of R. 2-3. Scan right to 1 past right end of R. 4. Print 1 at 1 past right end of R. 5-6. Scan left to 1 past left end of R (= right end of M). 7-8. Scan left to 1 past left end of M (= right end of L). 9. Print 0 at right end of L. 10-11. Scan left to 1 past left end of L. 12. Print 1 at 1 past left end of L. 13-14. Scan right to 1 past right end of L (= left end of M). 15-16. Scan right to 1 past right end of M (= left end of R). 17. Now scanning the 1 at left end of R (same position relative to L, M, and R as at start). Will always goto step 1. Start over.
Effect of 1 time through loop: R and L stay the same length, and all of R moves right one square, and all of L moves left one square, and M has an extra 2 0's.
As it runs, L and R pushed apart. Each loop, M has extra 2 0's.
Initial ...00011100111000... tape: | |
We have the optimal value trapped between bounds L < R, where initially L = 0 and R = M. Set Mid = (L + R)/2. L ("no") Mid (?) R("yes") |--------------|------------| if the bound of Mid gives a "yes" then change to: L ("no") R ("yes) |--------------|------------| and if bound of Mid gives a "no" then change to: L ("no") R ("yes) |--------------|------------| In this way the optimal value is trapped between bounds whose distance apart in halved at each stage. So in log2(M) steps, we will have the optimal value.