## CS 307: Final Exam Study Guide Answers

### Lisp Programs:

• Write Scheme function(s) that will translate a Scheme expression into an English phrase. Assume that the expression may contain functions + - * / sin cos; if the expression has two operands, conjoin them with ``and''. Example:
```   (exp->english '(+ (sin x) (cos y)))

==>   (the sum of the sine of x and the cosine of y)
```

```(define (exp->english x)
(if (pair? x)
(append (op->english (op x))
(exp->english (lhs x))
(if (null? (cddr x))       ; test for unary
'()                    ;  if unary, that's all
(cons 'and             ;  else do rhs also
(exp->english (rhs x)) ) ) )
(list x) ) )         ; base case: make a list for append

(define (op->english op)
(list 'the
(cadr (assoc op '((+ sum) (- difference) (* product)
(/ quotient) (sin sine) (cos cosine))))
'of))

(define op car)
```
• Write a Scheme program to calculate GPA from a list of sublists, (course grade). Grades are letters, with A worth 4 grade points, B 3 grade points, etc. Assume that the list is non-empty and that each course counts the same. Example:
```   (gpa '((cs307 a) (psy301 c)))

==>  3.0
```

```(define (gpa l)
(let ((sum 0.0))
(dolist (pair l)
(set! sum
'((a 4.) (b 3.) (c 2.)
(d 1.) (f 0.)))))) )
(/ sum (length l)) ))
```
• Write a function (pay hours rates) where the data formats are: hours = ((name hours-worked) ...) rates = ((name hourly-wage) ...). For each entry in hours, look up the corresponding hourly wage in the list rates (order is arbitrary), multiply hours worked and hourly wage to get pay, and print name and pay. Example:
```   (pay '((smith 3)) '((jones 4.50) (smith 6.00)))

==>   prints:  smith 18.0
```

```(define (pay hours rates)
(dolist (person hours)
(display (car person))
(display " ")
(newline) ) )
```
• Write function(s) (total items prices) that will compute the total cost of a list of things that are purchased. items is a list of sub-lists, items = ((dept item number) ...) giving the department, name of item, and number of that item that were purchased. prices is a list of item prices by department, prices = ((dept (item price) ...) ...). Example:
```   (total '((clothing jeans 3)
(hardware wrench 2))
'((hardware (saw 9.95) (wrench 4.00))
(clothing (socks 2.50) (jeans 19.95))))
==>   67.85       [remember to multiply by number of items]
```

```(define (total items prices)
(define dept car)
(let ((sum 0))
(dolist (it items)
(set! sum (+ sum
(* (number it)
(cdr (assoc (dept it)
prices))))))) )
sum))
```

• Write a function (ngreater tree m) that will return the number of numbers greater than m that appear in the given tree. Example:
```   (ngreater '(+ (* 88 x) (+ 3 7) (/ 17 z))
5)
==>   3
```

```(define (ngreater tree m)
(if (pair? tree)
(+ (ngreater (car tree) m)
(ngreater (cdr tree) m))
(if (and (number? tree) (> tree m)) 1 0)))
```

• Write a function (deriv e var) that finds the derivative of expression e with respect to a variable var. Assume that the expression e may contain constants (numbers), variables (symbols), and the binary operators + and *. Use these rules, where d/dx is derivative with respect to x:
```   d/dx(x) = 1  (derivative of x with respect to x is one)
d/dx(v) = 0  (derivative of any variable v other than x
with respect to x is zero)
d/dx(c) = 0  (derivative of a constant is zero)
d/dx(u + v) =  d/dx(u) + d/dx(v)
d/dx(u * v) =  u * d/dx(v) + v * d/dx(u)
```
Note that in the last two cases you must make new list structure (a new formula) as the result. Examples:
```   (deriv 'x 'x)         ==>  1
(deriv 'y 'x)         ==>  0
(deriv  5 'x)         ==>  0
(deriv  '(+ x 3) 'x)  ==>  (+ 1 0)
(deriv  '(+ (* x 3) 7) 'x)
==>  (+ (+ (* x 0) (* 3 1)) 0)
```

```(define (deriv e var)
(if (pair? e)
(case (car e)
((+) (list '+ (deriv (lhs e) var)
(deriv (rhs e) var)))
((*) (list '+ (list '* (lhs e) (deriv (rhs e) var))
(list '* (rhs e) (deriv (lhs e) var)))) )
(if (eqv? e var) 1 0)))
```

• Write a recursive function (english code) that will translate Scheme code into English. Assume that the Scheme code can contain expressions using binary operators + - * / = and Scheme functions set! and if. Examples:
```   (english 'x)  ==>  (x)
(english '(+ x 7))  ==>  (the sum of x and 7)
(english '(if (= (+ i j) 3) (set! k 7)))
==>  (if the sum of i and j equals 3 then set k to 7)
```

```(define (english code)
(if (pair? code)
(case (car code)
((+ - * /)
(append (list 'the (opword (car code)) 'of)
(english (lhs code))
'(and)
(english (rhs code))) )
((=)
(append (english (lhs code))
'(equals)
(english (rhs code))))
((if)
(append '(if) (english (lhs code))
'(then) (english (rhs code))
(if (null? (cdddr code)) '()
((set!)
(append (list 'set (lhs code) 'to)
(english (rhs code)))))
(list code)))

(define (opword op)
(cadr (assoc op '((+ sum) (* product) (- difference)
(/ quotient)))))
```

• Write a function deep-reverse that will reverse not only the top level of a list, but also any sub-lists it may contain, recursively. Example:
```(deep-reverse '(((a b) c) d))  ==>  (d (c (b a)))
```

```(define (deep-reverse l) (deep-rev l '()))

(define (deep-rev l result)
(if (pair? l)
(deep-rev (cdr l)
(cons (deep-reverse (car l))
result))
(if (null? l) result l) ) )
```

```(define (deep-reverse l)
(if (pair? l)
l))
```

• The genetic code is carried by DNA molecules. DNA is composed of matched base pairs, where bases are represented by the letters C, G, A, or T. C is always paired with G, and A is always paired with T. We will represent a DNA fragment as a list of the base letters of one side of the DNA helix.

The complement of a DNA sequence is a sequence of the complementary letters (A-T, C-G) of the given sequence. Write a function (complement dna) to compute the complement of a given string. Use auxiliary functions if you wish. Example:

```(complement '(a a a g t g c))  ==>  (t t t c a c g)
```

```(define (complement lst)             ; the easiest solution
(sublis '((a . t) (t . a) (c . g) (g . c)) lst))
```

```(define (complement lst) (reverse (complementb lst '())))

(define (complementb lst result)
(if (pair? lst)
(complementb (cdr lst)
(cons (opposite (car lst)) result))
result))

(define (opposite base)
(cdr (assoc base '((a . t) (t . a) (c . g) (g . c)) )))
```

• A DNA sequence codes for a sequence of amino acids that make up a protein. Each 3 letters of DNA code for one amino acid. Write a function (protein dna codes) to compute the sequence of amino acids specified by a DNA string. Assume (define codes '(((A A A) Phe) ((A T A) Tyr) ((G T G) His)...) gives the 3 DNA bases, followed by an abbreviation of the amino acid for which they code, for all 3-base sequences. Example:
```(protein '(a a a g t g a t a) codes)  =  (Phe His Tyr)
```

```(define (protein dna codes)
(if (pair? dna)
codes))
(protein (cdddr dna) codes))
'()))
```

```(define (protein dna codes) (proteinb dna codes '()))

(define (proteinb dna codes result)
(if (and (pair? dna) (pair? (cdr dna)) (pair? (cddr dna)))
(proteinb (cdddr dna) codes
codes))
result))
(reverse result)))
```

• A restriction enzyme is a molecule that will bind to a particular sequence of DNA bases, then cut the DNA at that point. Write a function (restrict dna enzyme) that returns a list of numbered locations at which a given dna string would be cut by a given enzyme. If the enzyme matches the front part of the dna, that would be location 0, etc. Both the dna and the enzyme may be of arbitrary length. Example:
```(restrict '(g t g a a a g t g a t a) '(t g a))  =  (1 7)
-----       -----
0 1 2 3 4 5 6 7 8 9 10
```

```(define (restrict dna enzyme) (restrictb dna enzyme 0 '()))

(define (restrictb dna enzyme position result)
(if (pair? dna)
(restrictb (cdr dna) enzyme (1+ position)
(if (matchenz dna enzyme)
(cons position result)
result))
(reverse result)))

(define (matchenz dna enzyme)   ; does enzyme match front of dna?
(if (pair? enzyme)
(if (pair? dna)
(if (eq? (car dna) (car enzyme))
(matchenz (cdr dna) (cdr enzyme))
#f)
#f)
#t))

(define (matchenz dna enzyme)   ; 2nd version
(or (null? enzyme)
(and (pair? dna)
(eq? (car dna) (car enzyme))
(matchenz (cdr dna) (cdr enzyme)))))
```
• One way to determine a long DNA sequence is to break it into shorter pieces, find the sequences of the pieces, and then re-assemble the pieces based on areas where they overlap with the same codes. Write function(s) (dnamatch one two) to compute the first location at which the back part of list one matches the front part of list two (return #f if no match).
```Example:  (dnamatch '(a a a g t g c) '(t g c g t g))  =  4
0 1 2 3 4 5 6    -----
```
(The sequence t g c matches beginning at position 4.)

```(define (dnamatch one two) (dnamatchb one two 0))

(define (dnamatchb one two n)
(if (pair? one)
(if (matchfront one two)
n
(dnamatchb (cdr one) two (1+ n)))
#f))

; see if list x matches front of list two.
; (matchfront '(a b c) '(a b c d e)) = #t
(define (matchfront x two)
(if (pair? x)
(and (pair? two)
(eq? (car x) (car two))
(matchfront (cdr x) (cdr two)))
#t))
```

• Write a function (combine one two) that will produce a combined DNA list given two lists that match as above. You may use dnamatch in writing this function.
```Example:  (combine '(a a a g t g c)
'(t g c g t g))
=  (a a a g t g c g t g)
```

```(define (combine one two)
(append one
(list-tail two (- (length one) (dnamatch one two)))) )
```

• Write a function (evalexp expr vals) to interpret (evaluate) an arithmetic expression. expr is an expression that may contain operators + - * /; - may be binary or unary. vals is an association list containing the values of variables. Note: for this problem, you may not use the functions sublis or eval; write an interpreter instead. Example:
```(evalexp '(+ a (* 3 b)) '((a . 7) (b . 8)))  =  31
```

```(define (evalexp expr vals)
(if (pair? expr)
(case (op expr)
((+) (+ (evalexp (lhs expr) vals) (evalexp (rhs expr) vals)))
((*) (* (evalexp (lhs expr) vals) (evalexp (rhs expr) vals)))
((/) (/ (evalexp (lhs expr) vals) (evalexp (rhs expr) vals)))
((-) (if (pair? (cddr expr))
(- (evalexp (lhs expr) vals) (evalexp (rhs expr) vals)))
(- (evalexp (lhs expr) vals))))
(if (symbol? expr)
(cdr (assoc expr vals))
expr)))
```

• A holiday mobile is either an ornament or a structure (left ornament right) where left and right are mobiles and ornament is an ornament. The weights of ornaments are given by an association list, weights.
• Write a function (weight mobile weights) to compute the weight of a mobile. Example:
```(weight '((star ball star) star ball)
'((ball . 4) (star . 2)))     =  14
```

```(define (weight mobile weights)
(if (pair? mobile)
(+ (weight (left mobile) weights)
(cdr (assoc (center mobile) weights))
(weight (right mobile) weights))
(cdr (assoc mobile weights))))
```

• Write a function (balanced mobile weights) to determine whether a mobile is balanced. A mobile is balanced if its left and right parts weigh the same and both of them are balanced. Example:
```(balanced '((star ball star) ball bell)
'((ball . 4) (star . 2) (bell . 8)))   =  #t
```

```(define (balanced mobile weights)
(define left car) (define right caddr)
(if (pair? mobile)
(and (balanced (left mobile) weights)
(= (weight (left mobile) weights)
(weight (right mobile) weights))
(balanced (right mobile) weights))
#t))
```
• Write function(s) (wlt scores) to determine the number of wins, losses, and ties given a list of game scores, each of which is (home-score opponent-score).
```Example:  (wlt '((14 7) (10 10) (21 24) (17 7)))
=  (2 1 1)         [2 wins, 1 loss, 1 tie]
```

```(define (wlt scores)
(let ((wins 0) (losses 0) (ties 0))
(dolist (game scores)
(cond ((> (car game) (cadr game)) (set! wins (1+ wins)))
((< (car game) (cadr game)) (set! losses (1+ losses)))
(else (set! ties (1+ ties)))))
(list wins losses ties)))
```
• Write a function (evens tree) that returns the product of all the even numbers in tree (which may contain some non-numbers).
```Example:  (evens '(a (2 3 4) (b (5 6))))  =  48
```

```(define (evens tree)
(if (pair? tree)
(* (evens (car tree))
(evens (cdr tree)))
(if (and (number? tree) (even? tree))
tree
1)))
```
• A robot mouse is to find a path through a maze. Each junction in the maze is either #t (the exit from the maze, which is the goal), #f (a wall blocking the mouse), or a list (left center right) of junctions. Write function(s) (mouse maze) to find a path through the maze. A path is a list of directions for the mouse (left, center, or right).
```Example:  (mouse '((#f #f #t) #f (#f #f #f))) = (left right)
```

```(define (mouse maze)
(if (pair? maze)
(if (mouse (car maze))
(cons 'left (mouse (car maze)))
#f)))
(if maze '() #f)))
```
• A stack machine is a kind of computer CPU that uses a stack for its internal storage. Write function(s) to simulate a stack machine: (sm instructions memory). memory is an association list ((variable value) ...). Use a list called stack, initialized to empty list, for the internal stack. instructions is a list of instructions:
```  (pushn n)  put the number n onto the front of the stack
(pushv v)  put the value of the variable v onto stack
(add)      remove the top two elements from the stack,
add them, and put the result back on the stack
(mul)      multiply (as above)
```
Return the top value on the stack.
```Example:  (sm '((pushv x) (pushn 7) (mul)) '((x 3)))  =  21
```

```(define (sm instructions memory)
(let ((stack '()))
(dolist (inst instructions)
(case (car inst)
stack)))
((pushn) (set! stack (cons (cadr inst) stack)))
(cddr stack))))
((mul) (set! stack (cons (* (car stack) (cadr stack))
(cddr stack)))) ) )
(car stack) ))
```
• Write function(s) (code e) to generate code for the stack machine from an arithmetic expression e using operators + and *. For variables or numbers, generate the appropriate push instruction; otherwise, generate code for operands first, then generate the appropriate operation.
```Example:  (code 'x)  =  ((pushv x))
(code '(+ x 3))  =  ((pushv x) (pushn 3) (add))
(code '(* a (+ b 3)))
=  ((pushv a) (pushv b) (pushn 3) (add) (mul))
```

```(define (code e) (reverse (codeb e '())))

(define (codeb e lst)
(if (pair? e)
(cons (cdr (assoc (car e) '((+ add) (* mul))))
(cons (if (symbol? e)
(list 'pushv e)
(list 'pushn e))
lst)))
```
• Write function(s) (backchain goal rules facts) to try to prove a goal given a set of rules and facts. facts is an association list ((var value) ...) that tells which variables are known to be true or false. rules is a list of rules of the form (conclusion premise1 ... premisen); each rule states that the conclusion is true if all of the premises are true. backchain should work as follows: if the goal is known to be #t or #f based on the list facts, return that value. Otherwise, try rules to see if some rule has the goal as conclusion and has premises that are true (using backchain).
```Example:  (backchain 'a '() '((a #t)))  =  #t
(backchain 'a '((a b)) '((b #t)))  =  #t
(backchain 'a '((a b c) (c d)) '((b #t) (d #t))) = #t
[the rules are "a is true if b and c are true",
"c is true if d is true"]
```

```(define (backchain goal rules facts)
(if (assoc goal facts)
(some (lambda (rule)
(and (eq? (car rule) goal)
(every (lambda (subgoal)
(backchain subgoal rules facts))
(cdr rule))))
rules)) )
```
• Write a function (ship order inventory) that creates a shipping list from an order and an inventory. Both order and inventory are lists ((item quantity) ...). Return a list of what was ordered, but without items that do not appear in the inventory list, and limiting the number shipped to the number actually in inventory.
Example:
```(ship '((widgets 2) (gizmos 7) (thingies 14))
'((thingies 12) (widgets 5) (grommets 3)))
=>  ((widgets 2) (thingies 12))
```

```(define (ship order inventory)
(if (pair? order)
(let ((inv (assoc (caar order) inventory)))
(if inv
(cons (list (caar order)
(ship (cdr order) inventory))
(ship (cdr order) inventory)))
'()))
```
• Write a function (limit tree m) that makes a copy of the tree, but replaces any number greater than m by m.
Example:
```           (limit '((9 to (5)) (spirit (of 76))) 7)
=>    ((7 to (5)) (spirit (of 7)))
```

```(define (limit tree m)
(if (pair? tree)
(cons (limit (car tree) m)
(limit (cdr tree) m))
(if (number? tree)
(min m tree)
tree)))
```
• A secret formula is composed of binary operators and operands in Scheme notation. To protect a secret formula, write a function (encrypt formula keylist) that exchanges the operands of an operator if the element of keylist is a 1 but leaves the order unchanged if it is a 0. The first element of keylist applies to the top level of the formula, etc.
Example:
```          (encrypt '(* (+ (/ a b) c) (- d (+ e f))) '(1 0 1))
=>  (* (- d (+ f e)) (+ (/ b a) c))
```

```(define op car)

(define (encrypt formula keylist)
(if (pair? formula)
(if (zero? (car keylist))
(list (op formula)
(encrypt (lhs formula) (cdr keylist))
(encrypt (rhs formula) (cdr keylist)))
(list (op formula)
(encrypt (rhs formula) (cdr keylist))
(encrypt (lhs formula) (cdr keylist))))
formula))
```
• Write function(s) (starmatch pattern input) that match a pattern list against an input list. The pattern list may contain a single *, which matches any number of symbols in the input list; the other symbols in the pattern and input lists must be equal. If the pattern matches, return the sublist of symbols that matches the *; otherwise, return #f.
Example:
```          (starmatch '(i feel * today)
'(i feel wild and crazy today))
=>  (wild and crazy)
```

```(define (starmatch pattern input)
(if (pair? pattern)
(if (eq? (car pattern) '*)
(starmatchb (cdr pattern) '() input)
(and (pair? input)
(eq? (car pattern) (car input))
(starmatch (cdr pattern) (cdr input))))
(if (null? input) '() #f)))

(define (starmatchb pattern ans input)
(if (equal? pattern input)
(reverse ans)
(if (pair? input)
(starmatchb pattern (cons (car input) ans)
(cdr input))
#f)))
```
• Write a psychiatrist program (doctor input patterns) that responds to a patient's input using patterns. Use starmatch to find a pattern whose input part matches; if no pattern matches, return '(tell me more). Insert the matching words into the output part of the pattern. To make the output sound correct, you must invert pronouns: replace I with you, my with your, myself with yourself.
Example:
```          (doctor '(i argued with my mother today)
'( ... ((i argued with * today)
(what did * say))...) )
=>  (what did your mother say)
```

```(define (doctor input patterns)
(let ((pat (some (lambda (pair)
(and (starmatch (car pair) input)
pair))
patterns)))
(if pat
(splice
(sublis '((i . you) (my . your) (myself . yourself))
(starmatch (car pat) input))
'(tell me more)) ))

(define (splice new pattern)
(if (pair? pattern)
(if (eq? (car pattern) '*)
(append new (cdr pattern))
(cons (car pattern)
(splice new (cdr pattern))))
'()))
```
• Electric power distribution in Cons City is structured as a binary tree. When lightning causes power outages, the power company collects outage reports into a tree structure (name lhs rhs) where name is a substation and lhs and rhs are subtrees or individual customers. Customers are #f if power is reported to be off, or #t otherwise. The power company wants to find the highest node that has failed and send a repair crew to fix it. A node has failed if both of its subtrees have failed, or if one or both customers below a bottom-level node are without power. Assuming all outages are due to a single substation failure and there are enough outage reports to identify it using the above rules, write a function (failure tree) to return the name of the top failing node, or #f if no failure.
Example:
```  (failure '(a (b #t #t) (d (e #f #f) (f #t #f))))
=>  d
```

```(define (failure tree)
(if (pair? tree)
(if (or (eq? (lhs tree) #f)
(eq? (rhs tree) #f)
(and (failure (lhs tree))
(failure (rhs tree))))
(car tree)
(or (failure (lhs tree))
(failure (rhs tree))))
#f))
```
• An explorer wishes to retrieve a prize from a cave. A cave is either a number > 0, representing the value of a prize, or a list (dist cave1 ... caven) where dist is the distance to the next junction and cave1 ... caven are the prizes or sub-caves accessible from the junction. The explorer cannot go deeper in the cave than the amount of rope available. Write a program (prize cave rope) that returns the maximum prize that the explorer can obtain.
Example:
```   (prize '(20 (10 5) (20 (10 100) 50) (20 40)) 45)
=>  50
```

```(define (prize cave rope)
(if (pair? cave)
(if (>= rope (car cave))
(let ((best 0))
(dolist (sub (cdr cave) best)
(set! best
(max best
(prize sub (- rope (car cave)))))))
0)
cave))
```

This elegant solution was suggested by a student:

```(define (prize cave rope)
(if (pair? cave)
(if (>= rope (car cave))
(apply max
(map (lambda (sub)
(prize sub (- rope (car cave))))
(cdr cave)))
0)
cave))
```
• A database relation is a list of field names and values, ((field value) ...). Write an interpreter (check relation test) to evaluate a test for a relation. A test may use binary operators and, or, =, or >, or the unary operator not; the operator = should be interpreted as equal? in Scheme. A symbol within a test has the value of that field in the relation. An item (quote value) within a relation yields the specified value. Note: For this problem, you may not use eval or sublis; write an interpreter instead.
Example:
```     (check '((name john) (age 27) (sex m) (major cs))
'(and (= sex 'm) (> age 21)) )
=>  #t
```

This function is similar to the version of eval in the class notes.

```(define (check relation test)
(if (pair? test)
(case (car test)
((and) (and (check relation (lhs test))
(check relation (rhs test))))
((or) (or (check relation (lhs test))
(check relation (rhs test))))
((not) (not (check relation (lhs test))))
((=) (equal? (check relation (lhs test))
(check relation (rhs test))))
((>) (> (check relation (lhs test))
(check relation (rhs test))))
(else #f))
(if (symbol? test)
test)))
```
• Write a function (query database test), where database is a list of relations, that returns a list of all relations that satisfy the test. You may use check as above.
Example:
``` (query '(((name john) (sex m))
((name jill) (sex f)))
'(= sex 'f))
=>  (((name jill) (sex f)))
```

```(define (query database test)
(subset (lambda (x) (check x test))
database))
```

• Write a function (deep-assoc item lists) that will retrieve the first sublist of lists, a list of lists, that contains the specified item. Example:
```(deep-assoc 'cat '((rat mouse shrew) (dog cat) (horse pig cow)))
=>  (dog cat)
```

```(define (deep-assoc item lists)
(if (pair? lists)
(if (member item (car lists))
(car lists)
(deep-assoc item (cdr lists)))
#f))
```

• Write a function (paraphrase sentence synonyms) that will generate a paraphrase of the given sentence (a list of words). Synonyms is a list of lists of words that have approximately the same meaning. You may use deep-assoc if you wish. The function (random n) will generate a random integer between 0 and (n - 1), inclusive. Choose a random synonym for each word that has a synonym (the synonym could be the same word); otherwise, use the original word. Example:
```(paraphrase '(my love is like a red rose)
'((scarlet crimson red) (flower rose posy) (love mate)))
=>  (my love is like a scarlet posy)
```

```(define (paraword word synonyms)
(let ((lst (deep-assoc word synonyms)))
(if lst
(list-ref lst (random (length lst)))
word)))

(define (paraphrase sentence synonyms)
(map (lambda (x) (paraword x synonyms))
sentence))
```

• Write a function (sanitize alist tree) that will 'sanitize' the tree by replacing each word that occurs as the first element of a sublist in alist by the second word in the sublist. Example:
```(sanitize '((guns toys) (dynamite candy-canes) (grenades lemons))
'(send (6 dynamite) and 12 grenades))
=> (send (6 candy-canes) and 12 lemons)
```

This is basically sublis with lists rather than dotted pairs.

```(define (sanitize alist tree)
(if (pair? tree)
(cons (sanitize alist (car tree))
(sanitize alist (cdr tree)))
(let ((pair (assoc tree alist)))
(if pair
tree) ) ))
```

• Write a function (half-list lst) that returns a list containing every other element of lst in the original order. The length of lst is arbitrary; be sure not to take cdr of (), which would generate an error. Example:
```(half-list '(a b c d e))  =>  (a c e)
```

```(define (half-list lst)
(if (pair? lst)
(cons (car lst)
(half-list (if (pair? (cdr lst))
(cddr lst)
'())))
'()))
```
• Write a function (shuffle lst) to shuffle a list. Use half-list to break the given list into two halves. Combine the two halves into a single list by calling (random 2) to generate a random number that is either 0 or 1: take the next element from the first half-list if it is 0, else from the other half- list. Each element of the original list should appear exactly once in the result. Example:
```(shuffle '(a b c d e f g h))  =>  (b a c e d f h g)
```

```(define (shuffle lst)
(if (pair? lst)
(shuffleb (half-list lst) (half-list (cdr lst)))
'()))

(define (shuffleb one two)
(if (pair? one)
(if (pair? two)
(if (zero? (random 2))
(cons (car one) (shuffleb (cdr one) two))
(cons (car two) (shuffleb one (cdr two))))
one)
two))
```
• Write function(s) (trip mileage tree) to plan an optimal vacation trip. mileage is the maximum number of miles that can be driven (one way). tree is a data structure (city miles value destinations) where city is the name of a city, miles is the number of miles to get to it from the preceding city, value is the value of visiting that city, and destinations is a list of trees that can be reached from that city. Return a list containing a list of city names and the maximum total value that can be obtained for the given mileage. Example:
```(trip 250 '(austin 0 200 ((waco 100 20 ((college-station 40 -100 ())
(dallas 120 200 ()))))))
=>  ((austin waco dallas) 420)
```

```(define city car)
; This is a tree search.
; Base case: not enough mileage to reach the current city;
;    return an empty list of cities and 0 points.
; Recursive case: subtract the miles for this city from the mileage,
; then find the best trip from this city.
; Return a list of: cons this city onto that trip,
;                   add points for this city to that trip's points.
(define (trip mileage tree)
(let ((best (list '() 0)) (new #f))
(if (< mileage (miles tree))
best
(dolist (d (destinations tree)
(list (cons (city tree) (car best))
(set! new (trip (- mileage (miles tree)) d))
(set! best new))))))
```

### Java Programs:

Examples:
• Write a Java function to find the average of an array of numbers.
```   public static double average( double[] arr ) {
double sum = 0.0;
int n = 0;
for ( int i=0; i < arr.length; i++ )
{ sum = sum + arr[i];
n++; };
return ( sum / (double) n ); }
```

A program similar to this is given in the lecture notes.

• Assume that an Employee object contains fields for the employee's name, salary, and boss, among other things. The boss field is a reference to the object for the employee's boss, or null for the president of the company. Write a Java function public static long level (Employee e) that determines the level of an employee in the company: the president has level 1, her subordinates have level 2, etc.

Note that this is the same as the length function: although the company structure is a tree structure, each employee object can be thought of as a list of the employee, the employee's boss, etc., terminating in the president. The level of the employee is the length of this list. Following the definition of the length function as given in the file Cons.java, we could write:

```    public static int level(Employee lst) {
int n = 0;
while ( lst != null )
{ n++;
lst = lst.boss();
}
return n; }
```

• Translate the following Scheme statements into equivalent Java statements:
• ```(set! x (vector-ref v i))
x = v[i];```
• ```(if (> i 7) (set! j (+ j 1)))
if (i > 7) j++;```
• ```(while (< i 3) (display i) (set! i (1+ i)))
while (i < 3) { System.out.print(i); i++; }```
• ```(dotimes (i 7) (set! sum (+ sum (vector-ref v i))))
for (i = 0; i < 7; i++) sum = sum + v[i];```
• ```(set! y (* 8 (sin x)))
y = 8 * Math.sin(x);```
• ```(set! x (+ y 2))
x = y + 2;```
• ```(set! y (* (exp (- x)) (sin x)))
y = Math.exp(- x) * Math.sin(x);```
• ```(dotimes (j 3) (vector-set! v j 0.0))
for (j = 0; j < 3; j++) v[j] = 0.0;```
• ```(while (< i 7) (set! i (+ i 1)))
while (i < 7) i = i + 1;```
• ```(if (> i 3) (display (vector-ref x i)))
if (i > 3) System.out.print(x[i]);```