{[ promptMessage ]}

Bookmark it

{[ promptMessage ]}

Data Str & Algorithm HW Solutions 7

Data Str & Algorithm HW Solutions 7 - Fibi computes...

Info iconThis preview shows page 1. Sign up to view the full content.

View Full Document Right Arrow Icon
7 bool isEmpty(); // Return the number of elements with a given valueint countInBag(int); 2.7 The list class ADT from Chapter 4 is a sequence. 2.8 long ifact(int n) { // make n <= 12 so n! for long int long fact = 1; Assert((n >= 0) && (n <= 12), "Input out of range"); for (int i=1; i<= n; i++) fact = fact * i; return fact; } 2.9 void rpermute(int *array, int n) { swap(array, n-1, Random(n)); rpermute(array, n-1); } 2.10 (a) Most people will fi nd the recursive form natural and easy to understand. The iterative version requires careful examination to understand what it does, or to have con fi dence that it works as claimed. (b) Fibr is so much slower than Fibi because Fibr re-computes the bulk of the series twice to get the two values to add. What is much worse, the recursive calls to compute the subexpressions also re-com- pute the bulk of the series, and do so recursively. The result is an expo- nential explosion. In contrast,
Background image of page 1
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: Fibi computes each value in the series exactly once, and so its running time is proportional to n . 2.11 // Array curr[i] indicates current position of ring i. void GenTOH(int n, POLE goal, POLE t1, POLE t2, POLE* curr) { if (curr[n] == goal) // Get top n-1 rings set up GenTOH(n-1, goal, t1, t2, curr); else { if (curr[n] == t1) swap(t1, t2); // Get names right // Now, ring n is on pole t2. Put others on t1. GenTOH(n-1, t1, goal, t2, curr); move(t2, goal); GenTOH(n-1, goal, t1, t2, curr); // Move n-1 back } } 2.12 At each step of the way, the reduction toward the base case is only half as far as the previous time. In theory, this series approaches, but never reaches, 0, so it will go on forever. In practice, the value should become computa-tionally indistinguishable from zero, and terminate. However, this is terrible programming practice....
View Full Document

{[ snackBarMessage ]}

Ask a homework question - tutors are online