CSE341 Sample Final Key handout #19 1. Expressions part A: (define a 1) (define b 2) (define c 3) (let ((b (+ 2 4)) (c (+ b 10))) (+ a b c)) 19 part B: (define a 3) (define b 4) (define c 5) (let* ((b (+ 2 4)) (c (+ b 10))) (+ a b c)) 25 part C: (define a 1) (define b (list a 2)) (set! a 3) (set-car! (cdr b) 4) (list a b) (3 (1 4)) Part D: (define a '(1 2)) (define b (cons 3 a)) (define c (append a b)) (set-car! a 4) (list a b c) ((4 2) (3 4 2) (1 2 3 4 2)) 2. One possible solution appears below. (define (count target lst) (cond ((null? lst) 0) ((equal? (car lst) target) (+ 1 (count target (cdr lst)))) (else (count target (cdr lst))))) 3. One possible solution appears below. (define (zip lst1 lst2) (if (or (null? lst1) (null? lst2)) () (cons (list (car lst1) (car lst2)) (zip (cdr lst1) (cdr lst2))))) 4. One possible solution appears below. (define (sum lst) (cond ((null? lst) 0) ((list? (car lst)) (+ (sum (car lst)) (sum (cdr lst)))) ((number? (car lst)) (+ (car lst) (sum (cdr lst)))) (else (sum (cdr lst))))) 5. One possible solution appears below. def posOf(short, long) for i in 0..(long.length - short.length) ok = true for j in 0..(short.length - 1) if long[i + j] != short[j] ok = false break end end if ok return i end end return -1 end 6. One possible solution appears below. def commonFactors(n1, n2) result = [] if n1 < n2 then n1.factors {|n| result.push n if n2 % n == 0} else n2.factors {|n| result.push n if n1 % n == 0} end return result end 7. One possible solution appears below. class Randomizer def initialize(m, n) @m = m @n = n end def each values = [] for i in @m..@n values.push i end # shuffle for i in 0..(values.length - 2) j = i + rand(values.length - i) temp = values[i] values[i] = values[j] values[j] = temp end values.each {|n| yield n} end end