SICP example: Counting change, cannot understand

后端 未结 3 1249
甜味超标
甜味超标 2020-11-30 07:47

I am a beginner following SICP course on MIT OpenCourseWare using both the video lectures and the book available online. Yesterday I came across an example, which ask if we

3条回答
  •  有刺的猬
    2020-11-30 08:35

    The first code box in Will Ness' answer above gave me enough insight to understand the algorithm. Once I understood it, I realized I'd probably have got there very quickly by actually seeing what the algorithm does step-by-step.

    Below is the graph of how the algorithm proceeds for a simple case. The amount is 6 pence and we have two kinds of coin: five pence (index 2) and a penny (index 1).

    Note that the leaf nodes all evaluate to 0 or 1. This is obvious when we look at the condition in the procedure (one of these values is returned, or else the function calls itself again.) Only two leaf nodes evaluate to 1, so there are 2 ways to make 6 pence from these two kinds of coin, i.e. 6 pennies, or a penny and a five pence.

    I now understand the algorithm but I still don't see how I would have worked out the algorithm from the initial problem. Maybe, as I read more of the SICP book, this kind of solution will seem more obvious to me.

                                 (cc 6 2)
                                    |
                     -----------------------------------
                     |                                 |
                  (cc 6 1)                          (cc 1 2)
                     |                                 |
       ------------------                         --------------
       |                |                         |            |
    (cc 6 0)=0       (cc 5 1)                  (cc 1 1)     (cc -4 2)=0
                        |                         |
                 -------------             -------------
                 |           |             |           |
              (cc 5 0)=0  (cc 4 1)      (cc 1 0)=0  (cc 0 1)=1
                             |
                   --------------
                   |            |
                (cc 4 0)=0   (cc 3 1)
                                |
                         --------------
                         |            |
                      (cc 3 0)=0   (cc 2 1)
                                      |
                               --------------
                               |            |
                            (cc 2 0)=0   (cc 1 1)
                                            |
                                     --------------
                                     |            |
                                  (cc 1 0)=0   (cc 0 1)=1
    

提交回复
热议问题