Representing an amount of money with specific bills

后端 未结 4 512
谎友^
谎友^ 2020-12-21 17:16

I want to write a function in Racket which takes an amount of money and a list of specific bill-values, and then returns a list with the amount of bills used of every type t

4条回答
  •  半阙折子戏
    2020-12-21 17:38

    Your procedure does too much and you use mutation which is uneccesary. If you split the problem up.

    (define (calc-one-bill n bill)
      ...)
    
    ;; test 
    (calc-one-bill 450 100) ; ==> 4
    (calc-one-bill 450 50)  ; ==> 9
    

    Then you can make:

    (define (calc-new-n n bill amount)
      ...)
    
    (calc-new-n 450 100 4) ; ==> 50
    (calc-new-n 450 50 9)  ; ==> 0
    

    Then you can reduce your original implememntation like this:

    (define (calc n bills)
      (if (null? bills)
          (if (zero? n)
              '()
              (error "The unit needs to be the last element in the bills list"))
          (let* ((bill (car bills))
                 (amount (calc-one-bill n bill)))
            (cons amount
                  (calc (calc-new-n n bill amount)
                        (cdr bills))))))
    

    This will always choose the solution with fewest bills, just as your version seems to do. Both versions requires that the last element in the bill passed is the unit 1. For a more complex method, that works with (calc 406 (list 100 10 5 2)) and that potentially can find all combinations of solutions, see Will's answer.

提交回复
热议问题