S4. Test 2 Solutions

posted Oct 19, 2012, 6:10 AM by Samuel Konstantinovich   [ updated Nov 15, 2012, 5:13 AM ]
;Continue working on labs 4-6. 
;Lab4: skip maxHail if you get stuck
;Lab5: if getNth is too tricky, try length first. 
;Lab6: after you can differentiate between cons/append
;      try writing functions:  
;      a. (reverse L)  hint: use append
;      b. (removeNth L n) deletes the value at the nth position
;             if the n is longer than the list then return the list
;      c. (insertNth L n value)  places the value in the list 
;            at the nth position. If the n is longer than the list 
;            place the value at the end of the list. 

;SAMPLE SOLUTIONS to test problems 
;Between
(define (between x a b)
  (or (and (< x a) (> x b))
      (and (> x a) (< x b))))

(define (between x a b)
  (or (< a x b) (< b x a)))
  
;Sum of Squares:
(define (sumOfSquares n)
  (if (= n 0) 0 (+ (* n n) (sumOfSquares (- n 1)))))


;CountDigitsMoreThan:

;useful function to help
(define (singleDigit? n)
   (= 0 (quotient n 10)))

;naive solution: extra booleans
;positive side effect: you can change the order of the cond 
;without breaking the function
(define (countDigitsMoreThan n v)
  (cond
    ( (and (< n v)  (singleDigit? n)) 0)
    ( (and (> n v)  (singleDigit? n)) 1)
    ( (and (< n v) (not (singleDigit? n))) (countDigitsMoreThan (quotient n 10)v))
    ( (and (> n v) (not (singleDigit? n))) (+ 1 (countDigitsMoreThan (quotient n 10)v)))))

;Standard solution: 4 way cond statement
(define (countDigitsMoreThan n v)
  (cond
    ( (and (> n v) (singleDigit? n)) 1)
    ( (singleDigit? n) 0)
    ( (> (remainder n 10) v) (+ 1 (countDigitsMoreThan (quotient n 10)v)))
    ( else  (countDigitsMoreThan (quotient n 10)v))))

;Insightful Solution: 3 way cond statement
(define (countDigitsMoreThan n v)
  (cond
    ( (and (> n v) (singleDigit? n)) 1)
    ( (singleDigit? n) 0)
    ( else (+ 
            (countDigitsMoreThan (remainder n 10)v)
            (countDigitsMoreThan (quotient n 10)v)))))

;(countDigitsMoreThan 12345679 0)
;(countDigitsMoreThan 12345679 2)
;(countDigitsMoreThan 12345679 3)

;SumSequence  1  -1/2   1/3   -1/4    1/5   -1/6     1/7    -1/8  .... (sumSequence n)
  (cond
    ((= n 1) 1)
    ((even? n) (+ (/ -1 n) (sumSequence (- n 1))))
    (else      (+ (/ 1 n) (sumSequence (- n 1))))))
;(newline)
;(* 1.0(sumSequence 1))
;(* 1.0(sumSequence 2))
;(* 1.0(sumSequence 3))
;(* 1.0(sumSequence 4))

Comments