Sheet1
Page 1
CS 61AWeek 4 solutions
HOMEWORK:
---------
1.
Start by tracing it out (mentally or online):
(fact 5)
(iter 1 1)
(iter 1 2)
(iter 2 3)
(iter 6 4)
(iter 24 5)
(iter 120 6)
What jumps out is that the first argument to ITER is always the factorial
of something.
Of what?
One less than the second argument.
So the
invariant is
product = (counter-1)!
2.
Tracing again:
(fact 5)
(helper 1 5)
(helper 5 4)
(helper 20 3)
(helper 60 2)
(helper 120 1)
(helper 120 0)
This time, RESULT isn't the factorial of anything until the end.
The
invariant is a little harder to find, but at each step, the work still
undone is the factorial of COUNTER, so the invariant turns out to be
n! = result * counter!
3.
Trace:
(pigl 'scheme)
(pighelp 'scheme)
(pighelp 'chemes)
(pighelp 'hemesc)
(pighelp 'emesch)
What's invariant is that all of these words have the same translation
into Pig Latin:
(pigl wd) = (pigl wrd)
4.
In question 3, we had the name WD for our original argument, and the
name WRD for the current argument to the helper.
In the simpler procedure,
This
preview
has intentionally blurred sections.
Sign up to view the full version.
Sheet1
Page 2

This is the end of the preview.
Sign up
to
access the rest of the document.
- Spring '08
- mckenzie
-
Click to edit the document details