10-26-2013

posted Oct 30, 2013, 5:30 AM by Samuel Konstantinovich   [ updated Oct 30, 2013, 5:30 AM ]
Some solutions:

Length and sum of a list of integers with no sublists.
(define (lengthList L)
  (if (null? L) 
      0
      (+ 1 (lengthList (cdr L)))))

(define (sumList L)
  (if (null? L) 
      0
      (+ (car L) (sumList (cdr L)))))


The value of the largest integer in a nonempty list of integers:
(define (maxOfList L)
  (if (=(length L) 1) 
      (car L)
      (max (car L) (maxOfList (cdr L)))))


Count the number of even elements of a list of inegers.
Solution1:
(define (valueOf x)
  (if (even? x) 1 0));

(define (countEven L)
  (if (null? L) 
      0
      (+ (valueOf (car L)) (countEven (cdr L)))))


Solution2:
(define (countEven L)
  (cond
    ((null? L)      0)
    ((even? (car L))  (+ 1 (countEven (cdr L))))
    (else  (countEven (cdr L)))))



GCD Solution:

(define (myGCD a b)
  (if (= b 0)
      a
      (myGCD b (remainder a b))))


Count empty sublists in a list WITH sublists:
(define (countEmpty L);with sublists
  (cond
    ( (null? L) 0) 
    ( (null? (car L)) (+ 1 (countEmpty (cdr L))))
    ( (list? (car L)) (+ (countEmpty (car L)) (countEmpty (cdr L))))
    ( else (countEmpty (cdr L)))))



MaxHail 
version 1:
(define (maxHail n)
  (cond 
    ( (= n 1) 1)
    ( (even? n)  (max n (maxHail (/ n 2) ) ) )
    ( else  (max n (maxHail (+ (* 3 n) 1) ) ) )
) )

version 2:
(define (hail n)
  (cond 
    ( (= n 1) 1)
    ( (even? n) (/ n 2) )
    ( (odd? n) (+ (* n 3) 1))))

(define (maxHail n)
  (if (= n 1) 
      1
      (max n (maxHail (hail n)))))








Comments