No idea how to solve SICP exercise 1.11

后端 未结 6 1705
感动是毒
感动是毒 2021-02-01 03:59

Exercise 1.11:

A function f is defined by the rule that f(n) = n if n < 3 and f(n) = f(n - 1) + 2f(n - 2)

6条回答
  •  遥遥无期
    2021-02-01 04:30

    What did help me was running the process manually using a pencil and using hint author gave for the fibonacci example

    a <- a + b
    b <- a
    

    Translating this to new problem is how you push state forward in the process

    a <- a + (b * 2) + (c * 3)
    b <- a
    c <- b
    

    So you need a function with an interface to accept 3 variables: a, b, c. And it needs to call itself using process above.

    (define (f-iter a b c)
      (f-iter (+ a (* b 2) (* c 3)) a b))
    

    If you run and print each variable for each iteration starting with (f-iter 1 0 0), you'll get something like this (it will run forever of course):

    a   b   c
    =========
    1   0   0
    1   1   0
    3   1   1
    8   3   1
    17  8   3
    42  17  8
    100 42  17
    235 100 42
    ...
    

    Can you see the answer? You get it by summing columns b and c for each iteration. I must admit I found it by doing some trail and error. Only thing left is having a counter to know when to stop, here is the whole thing:

    (define (f n)
      (f-iter 1 0 0 n))
    
    (define (f-iter a b c count)
      (if (= count 0)
          (+ b c)
          (f-iter (+ a (* b 2) (* c 3)) a b (- count 1))))
    

提交回复
热议问题