Exercise 1.11.
1). recursive one
(define (f-rec n)
(if (< n 4)
n
(+ (f-rec (- n 1))
(* 2 (f-rec (- n 2)))
(* 3 (f-rec (- n 3))))))
2). iterative one
a = (f 1)
b = (f 2)
c = (f 3)
Each update will get:
new a <== orig b
new b <== orig c
new c <== orig 3a+2b+c
(define (f-iter n)
(define (f-iter-iter a b c ix)
(if (= ix n)
a
(f-iter-iter b
c
(+ c (* 2 b) (* 3 a))
(+ ix 1))))
(f-iter-iter 1 2 3 1))
(f-rec 5)
(f-iter 5)
Exercise 1.12.
The counting of columns and rows all start from 1.
The elements on the shoulders of element(row,col) are:
(row-1,col-1) and (row-1,col)
(Only if (row, col) is not on the edge of Pascal's Triangle.)
(define (pascal-triangle row ix)
(cond ((= ix 1) 1)
((= ix row) 1)
(else (+ (pascal-triangle (- row 1) (- ix 1))
(pascal-triangle (- row 1) ix)))))
(pascal-triangle 4 3)
(pascal-triangle 1 1)
(pascal-triangle 5 2)
And I haven't taken illegal inputs into consideration.
Saturday, August 23, 2008
Subscribe to:
Post Comments (Atom)

0 comments:
Post a Comment