*Assigned:* Wednesday, April 25

*Due:* Tuesday, May 1, 11:59 p.m.

*Read the entire exam before you begin.*

There are ten problems on the exam. Some problems have subproblems. Each problem is worth ten (10) points. Although each problem is worth the same number of points, problems are not necessarily equal in difficulty.

This is a take-home examination. You may use any time or times you deem appropriate to complete the exam, provided you return it to me by the due date.

I expect that someone who has mastered the material and works at a moderate rate should have little trouble completing the exam in a reasonable amount of time. In particular, this exam is likely to take you about four to six hours, depending on how well you've learned topics and how fast you work. You should not work more than six hours on this exam. Stop at six hours and write “There's more to life than CS” and you will earn at least 70 points on this exam.

I would also appreciate it if you would write down the amount of time each problem takes. Each person who does so will earn two points of extra credit. Since I worry about the amount of time my exams take, I will give two points of extra credit to the first two people who honestly report that they've spent at least five hours on the exam or completed the exam. (At that point, I may then change the exam.)

This examination is open book, open notes, open mind, open computer, open Web. However, it is closed person. That means you should not talk to other people about the exam. In particular, CS mentors and tutors are instructed not to help you with exam problems. Other than as restricted by that limitation, you should feel free to use all reasonable resources available to you. As always, you are expected to turn in your own work. If you find ideas in a book or on the Web, be sure to cite them appropriately.

Although you may use the Web for this exam, you may not post your answers to this examination on the Web. And, in case it's not clear, you may not ask others (in person, via email, via IM, by posting a please help message, or in any other way) to put answers on the Web.

Because different students may be taking the exam at different times, you are not permitted to discuss the exam with anyone until after I have returned it. If you must say something about the exam, you are allowed to say “This is among the hardest exams I have ever taken. If you don't start it early, you will have no chance of finishing the exam.” You may also summarize these policies. You may not tell other students which problems you've finished. You may not tell other students how long you've spent on the exam.

You must include both of the following statements on the cover sheet of the examination.

- I have neither received nor given inappropriate assistance on this examination.
- I am not aware of any other students who have given or received inappropriate assistance on this examination.

Please sign and date each statement. Note that the statements must be true; if you are unable to sign either statement, please talk to me at your earliest convenience. You need not reveal the particulars of the dishonesty, simply that it happened. Note also that inappropriate assistance is assistance from (or to) anyone other than Professor Davis.

You must present your exam to me in two forms: both physically and electronically. That is, you must write all of your answers using the computer, print them out, number the pages, put your name on the top of every page, and hand me the printed copy. You must also email me a copy of your exam. You should create the emailed version by copying the various parts of your exam and pasting them into an email message. In both cases, you should put your answers in the same order as the problems. Failure to name and number the printed pages will lead to a penalty of two points. Failure to turn in both versions may lead to a much worse penalty.

In many problems, I ask you to write code. Unless I specify otherwise in a problem, you should write working code and include examples that show that you've tested the code. Do not include images; I should be able to regenerate those.

Your code should exhibit good style:

- Document each procedure using the 6Ps format for each procedure, unless directed otherwise.
- Comments are part of your code; introductory comments should be
*comments*marked using the semicolon (“;”) character and should appear*before*the procedure definition. - Use proper Scheme indentation. Be careful when cutting and pasting code as indentation is often not preserved.
- Choose meaningful procedure and parameter names. If the problem specifies particular names, then use the specified names.

Just as you should be careful and precise when you write code and documentation, so should you be careful and precise when you write prose. Please check your spelling and grammar. Since I should be equally careful, the whole class will receive one point of extra credit for each error in spelling or grammar you identify on this exam. Unless I make an extraordinary number of errors, I will limit that form of extra credit to five points.

I will give partial credit for partially correct answers. You ensure the best possible grade for yourself by emphasizing your answer and including a clear set of work that you used to derive the answer.

I may not be available at the time you take the exam. If you feel that a question is badly worded or impossible to answer, note the problem you have observed and attempt to reword the question in such a way that it is answerable. If it's a reasonable hour (before 9 p.m. and after 8 a.m.), feel free to try to call me in the office (269-4306) or at home (206-383-8798).

I will also reserve time at the start of classes next week to discuss any general questions you have on the exam.

`map`

`map`

*Topics:*
Higher-order procedures, analyzing efficiency.

In problem 2 of the lab on higher-order procedures, we asked you to consider four expressions to generate the successors of the squares of the first ten positive integers, similar to the following.

(my-map increment (my-map square (my-map increment (iota 10)))) (my-map (lambda (i) (increment (square (increment i)))) (iota 10)) (my-map (compose increment (compose square increment)) (iota 10)) (my-map (o increment square increment) (iota 10))

Many of you wrote that you preferred the last approach because it is most concise, but few of you mentioned efficiency.

Write, but do not document, your own version of map,
`(`

.
Then, use the tools from the lab on
analysis to analyze the number of times
`my-map`

`func`

* lst*)

`my-map`

is called
in evaluating each of the expressions above, or similar expressions that
vary the parameter to `iota`

.
Finally, write a short
paragraph characterizing the efficiency of the four expressions.
*Topics:*
Strings, higher-order procedures, efficiency vs. concision.

Write a function,
`(`

, which produces a new string in which
`string-map`

`func`

* str*)

`func`

`str`

Note that there is a tradeoff between conciseness and efficiency. In your documentation, include a 7th “P”, Philosophy. Under this heading, explain which goal you chose and why.

For example:

>`(string-map char-upcase "Banana")`

`"BANANA"`

>`(string-map char-downcase "Banana")`

`"banana"`

>`(string-map (o integer->char increment char->integer) "Banana")`

`"Cbobob"`

>`(string-map (o integer->char increment char->integer) "Apple")`

`"Bqqmf"`

>`(string-map (o integer->char (l-s + 65) (l-s - 90) char->integer char-upcase) "Banana")`

`"YZMZMZ"`

*Topics:*
Strings, characters, anonymous procedures, conciseness.

(a) Write, but do not document, a procedure
`(`

that transforms every upper-case letter
in `string-invert-case`

* str*)

`str`

`string-map`

.)
For example:

>`(string-invert-case "Banana")`

`"bANANA"`

>`(string-invert-case "Banana?!")`

`"bANANA?!"`

>`(string-invert-case "davisjan@cs.GRINNELL.edu")`

`"DAVISJAN@CS.grinnell.EDU"`

>`(string-invert-case "This Is Silly")`

`"tHIS iS sILLY"`

(b) Write, but do not document, a procedure
`(`

that produces a new string where
every instance of the old character has been replaced with the
specified new character.
Make your definition as concise as possible.
`string-replace-char`

`str`

`old`

* new*)

`string-map`

.)
For example:

>`(string-replace-char "Banana" #\a #\i)`

`"Binini"`

>`(string-replace-char "Barbeque" #\b #\f)`

`"Farfeque"`

>`(string-replace-char "Unchanged" #\x #\q)`

`"Unchanged"`

*Topics:*
Trees, vectors, searching, abstraction.

This problem is inspired by Rhys Price-Jones' visit to our class.

Consider an alternate definition of a tree where each node in the tree
is a vector containing three items: a record, a left child, and a right child.
Like an empty list, an empty tree is `null`

.
We might define the following procedures over this new kind of trees:

(define tree-node vector) (define tree-get-record (r-s vector-ref 0)) (define tree-get-left-child (r-s vector-ref 1)) (define tree-get-right-child (r-s vector-ref 2)) (define tree-empty? null?)

In a *binary search tree*, we guarantee that all the
records in the left child may precede the record at the current node, and the
record at the current node may precede all the records in the right child.
As an example, consider the following definition of a tree and a diagram
of the same tree. You should verify that all of the records in the left
subtree come alphabetically before “red”, and all the records
in the right subtree come alphabetically after “red”.

(define color-database (tree-node (list "red" 255 0 0) (tree-node (list "green" 0 128 0) (tree-node (list "blue" 0 0 255) null null) (tree-node (list "orange" 255 165 0) null null)) (tree-node (list "yellow" 255 255 0) null null))) |

As in an association list or a sorted vector of records, we would like to be able to search the tree for a record that has a specific key. For example:

>`(tree-search color-database "yellow" car string-ci<=?)`

`("yellow" 255 255 0)`

>`(tree-search color-database "red" car string-ci<=?)`

`("red" 255 0 0)`

>`(tree-search color-database "blue" car string-ci<=?)`

`("blue" 0 0 255)`

>`(tree-search color-database "plaid" car string-ci<=?)`

`#f`

The code below gives a skeleton of a `tree-search`

procedure. Your job is to complete this procedure definition.
You need not document `tree-search`

.

(define tree-search (lambda (tree key get-key may-precede?) (if (tree-empty? tree) ______ (let* ((record (tree-get-record tree)) (left? (may-precede? key (get-key record))) (right? (may-precede? (get-key record) key))) (cond ((and left? right?) __________________) (left? _________________________________) (right? _________________________________))))))

*Topics*: Sorting, vectors, numeric recursion, local
procedure bindings, reading documentation.

The famous *selection sort* algorithm for sorting
vectors works by repeatedly stepping through the vector from back
to front, swapping the largest remaining thing to the next place in
the vector. We might express that algorithm for a vector of strings as

(define string-vector-selection-sort! (lambda (strings) (let kernel ((pos (- (vector-length strings) 1))) (if (< pos 0) strings (let* ((index (string-vector-index-of-largest strings pos)) (largest (vector-ref strings index))) (vector-set! strings index (vector-ref strings pos)) (vector-set! strings pos largest) (kernel (- pos 1)))))))

Of course, we will need the procedure
`string-vector-index-of-largest`

, which
we might document as

;;; Procedure: ;;; string-vector-index-of-largest ;;; Parameters: ;;; strings, a vector of strings ;;; pos, an integer ;;; Purpose: ;;; Find the index of the alphabetically last string in the ;;; subvector of strings at positions [0..pos]. ;;; Produces: ;;; index, an integer ;;; Preconditions: ;;; pos > 0. ;;; (vector-length strings) > pos. ;;; Postconditions: ;;; For all i from 0 to pos, inclusive, ;;; (string-ci>=? (vector-ref strings index) (vector-ref strings i))

For example,

`>`

`(define claim (vector "computers" "are" "sentient" "and" "malicious" "on" "tv"))`

`>`

`(string-vector-index-of-largest claim 6)`

`6`

`>`

`(vector-ref claim 6)`

`"tv"`

`>`

`(string-vector-index-of-largest claim 5)`

`2`

`>`

`(vector-ref claim 2)`

`"sentient"`

`>`

`(string-vector-selection-sort! claim)`

`#("and" "are" "computers" "malicious" "on" "sentient" "tv")`

Implement the `string-vector-index-of-largest`

procedure.

*Topics:* Higher-order procedures.

Document and write a procedure, `(`

that returns
the function `polynomial-term`

`c`

* n*)

For example,

`>`

`(define two-x-cubed (polynomial-term 2 3))`

`>`

`(two-x-cubed 1)`

`2 ; 2 * 1 * 1 * 1`

`>`

`(two-x-cubed 3)`

`54 ; 2 * 3 * 3 * 3`

`>`

`(two-x-cubed 5)`

`250 ; 2 * 5 * 5 * 5`

`>`

`(define three-x-squared (polynomial-term 3 2))`

`>`

`(three-x-squared 1)`

`3 ; 3 * 1 * 1`

`>`

`(three-x-squared 3)`

`27 ; 3 * 3 * 3`

`>`

`(three-x-squared 5)`

`75 ; 3 * 5 * 5`

`>`

`((polynomial-term 5 4) 2)`

`80 ; 5 * 2^4`

*Topics:* Higher-order procedures.

Write, but do not document, a procedure
`(`

that takes a list of coefficients for the terms x`polynomial`

* coefs*)

`>`

; Create the polynomial f(x) = 1*x^0 + 4*x^1 = 1 + 4*x`(define line (polynomial (list 1 4)))`

`>`

; Evaluate f(5) = 1 + 4*5`(line 5)`

`21`

`>`

; Create the polynomial g(x) = 1 + 4*x + 3*x^2 - 2*x^3`(define cubic (polynomial (list 1 4 3 -2)))`

`>`

; Evaluate g(5) = 1 + 4*5 + 3*5^2 - 2*5^3`(cubic 5)`

`-154`

*Note:* You should try to make your solution as
concise and readable as possible
(even at the potential cost of some efficiency).

*Note:* Since a polynomial normally has at least one
term, you may assume that the list has at least one term. You need not
check this precondition (or any precondition, for that matter).

*Topics:* Divide-and-conquer, numeric recursion,
local procedure bindings.

We learned the *divide-and-conquer* strategy when
studying binary search. We have also applied that strategy to the
problem of sorting. Let's consider one other
instance in which divide-and-conquer may help: computing cube roots.

To compute the cube root of a number, `n`

, we start with two
estimates, one that we know is lower than the cube root and one that we
know is higher than the cube root. We repeatedly find the average of
those two numbers and refine our guess. We stop when the cube of
the average is “close enough” to `n`

.

What should we start as the lower-bound and upper-bound of the cube
root? Well, if *n* is at least 1, we can use
0 as the lower-bound and *n* as the upper bound.

For example, our procedure produces the following sequence of guesses to find the cube root of 2 with an accuracy of 3 decimal places.

`>`

`(cube-root 2.0)`

`(lower: 0.0 upper: 2.0 avg: 1.0 avg-cubed: 1.0) (lower: 1.0 upper: 2.0 avg: 1.5 avg-cubed: 3.375) (lower: 1.0 upper: 1.5 avg: 1.25 avg-cubed: 1.953125) (lower: 1.25 upper: 1.5 avg: 1.375 avg-cubed: 2.599609375) (lower: 1.25 upper: 1.375 avg: 1.3125 avg-cubed: 2.260986328) (lower: 1.25 upper: 1.3125 avg: 1.28125 avg-cubed: 2.103302002) (lower: 1.25 upper: 1.28125 avg: 1.265625 avg-cubed: 2.02728653) (lower: 1.25 upper: 1.265625 avg: 1.2578125 avg-cubed: 1.989975452) (lower: 1.2578125 upper: 1.265625 avg: 1.26171875 avg-cubed: 2.008573234) (lower: 1.2578125 upper: 1.26171875 avg: 1.259765625 avg-cubed: 1.999259926)`

`1.259765625`

Write, but do not document a procedure, `(`

, which should approximate the cube
root of `cube-root`

* n*)

`n`

`n`

`(``cube-root`

`n`

)

should be less than 0.001. You can assume that `n`

*Topics:* Numeric recursion, randomness.

Consider the following algorithm for drawing a shape.

Repeat many times:- Choose a random position in the image.
- If that position falls inside the shape, then color the pixel at that position.

We call this a *Monte Carlo method*; just like there is
randomness at a casino, there is randomness in our method. You could
think of this approach to drawing as like spray-painting through a
stencil: each
position inside the shape has some probability of being painted, but it's
unpredictable which ones will actually be chosen.

Write, but do not document, a procedure
`(`

.
Your procedure should use the following algorithm.
`spraypaint-quarter-circle`

`radius`

`n`

* color*)

Create an image of size radius x radius. Do the following n times: Select a random column and row within the image. If the distance from that point to the origin is less than radius, then color the pixel. Produce the image.

The result should look something like this:

>`(image-show (spraypaint-quarter-circle 100 5000 RGB-BLACK))`

The technique you just used to “spray-paint” a quarter-circle forms the basis of a Monte Carlo method for estimating the value of pi.

Consider the quarter-circle with radius 1. We select N random points where both the x and y values fall between 0 and 1. As we go along, count how many of those points fall within the quarter-circle; call this M.

Observe that M/N is equal to the ratio between the area of the quarter-circle and the area of the unit square. So, we estimate that pi is approximately M/N * 4, and produce this value.

The larger N is, the better our estimate will be.

Write and document `(`

which implements this algorithm.
`estimate-pi`

* n*)

In your sample output, show that providing larger values of N leads to increasingly precise estimates. For example:

`>`

`pi`

`3.141592653589793`

`>`

`(estimate-pi 10)`

`3.6`

`>`

`(estimate-pi 100)`

`3.0`

`>`

`(estimate-pi 1000)`

`3.204`

`>`

`(estimate-pi 10000)`

`3.1304`

`>`

`(estimate-pi 100000)`

`3.1503`

`>`

`(estimate-pi 1000000)`

`3.141568`

Here we will post answers to questions of general interest. Please check here before emailing your questions!

Here you will find errors of spelling, grammar, and design that students have noted. Remember, each error found corresponds to a point of extra credit for everyone. We usually limit such extra credit to five points. However, if we make an astoundingly large number of errors, then we will provide more extra credit.

- Misspelled “parameter” as “paramter”. [JY, 1 point]
- Also misspelled “indentation”, “preferred”, and “extraordinary”. Ran spell-checker. [DJ, 3 points]
- Used inconsistent procedure names in Problem 10. [AK, 1 point]