HW5.5 + Solutions

posted Oct 24, 2012, 5:54 AM by Samuel Konstantinovich   [ updated Oct 28, 2012, 6:20 AM ]
DO NOT SUBMIT ON HW SERVER 

Print AND STAPLE the following 8 Functions from your labs/practice problems:
BRING TO CLASS ON 10/25/2012

Practice Problems (from the 10/22, 10/23 lecture notes)
1. (countOdd L)
2. (create n)
3. (double L)
LAB4
4. (hailstone n)
5. (hailLength n)
LAB5
6. (getNthPlace L n)
7. (myLength L)
8. (countZeros L)

a. DO NOT PRINT : Things I wrote such as Questions or comments
b. You MAY print your own comments  
c. As per my HW policy : Your name must be printed on it.
d. It should be stapled if it is multiple pages!

DO NOT STAPLE IN CLASS. YOU WILL NOT HAVE TIME TO BORROW A STAPLER. (Because you will be taking a quiz on lists)
Solutions:
(define (countOdd L)
  (cond
    ((null? L) 0)
    ((odd? (car L)) (+ 1 (countOdd (cdr L))))
    (else           (countOdd (cdr L)))))
;OR
(define (countOdd L)
  (cond
    ((null? L) 0)
    (else (+ (if(odd? (car L))1 0) (countOdd (cdr L))))))

;Two different ways of writing create
(define (create N)
  (if (= N 0)
      '()
      (cons (* N N) (create (- N 1)))))

(define (createForwards N)
  (if (= N 0)
      '()
      (append (createForwards (- N 1))(list (* N N)))))


(define (double Q)
  (cond
    ((null? Q) '())
    (else (cons (* 2 (car Q))(double (cdr Q))))))


(define (hailstone n)
  (cond
    ((= n 1) (display 1))
    ((even? n) (begin
                 (display n)
                 (display ",")
                 (hailstone (/ n 2))))
    (else (begin
            (display n)
            (display ",")
            (hailstone (+ 1 (* 3 n)))))))

(define (hailLength n)
  (cond
    ((= n 1) 1)
    ((even? n) (+ 1 (hailLength (/ n 2))))
    (else      (+ 1 (hailLength (+ 1 (* 3 n)))))))

;Answer to one of the challenge problems:
;notice how similar the solution is to hailLength
(define (maxHail n)
  (cond
    ((= n 1) 1)
    ((even? n) (max n (maxHail (/ n 2))))
    (else      (max n (maxHail (+ 1 (* 3 n)))))))

(define (getNth L n)
  (cond 
    ((null? L) "error, I didn't say what to do when you reach the end of a list")
    ((= n 0) (car L))
    (else (getNth (cdr L) (- n 1)))))

(define (myLength L)
  (cond 
    ((null? L) 0)
    (else (+ 1 (myLength (cdr L))))))


(define (countZeros L)
  (cond 
    ((null? L) 0)
    ((= 0 (car L))  (+ 1 (countZeros (cdr L))))
    (else  (countZeros (cdr L)))))



Comments