Representing an amount of money with specific bills

后端 未结 4 505
谎友^
谎友^ 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:34

    I think this is the first program I wrote when learning FORTRAN! Here is a version which makes no bones about using everything Racket has to offer (or, at least, everything I know about). As such it's probably a terrible homework solution, and it's certainly prettier than the FORTRAN I wrote in 1984.

    Note that this version doesn't search, so it will get remainders even when it does not need to. It never gets a remainder if the lowest denomination is 1, of course.

    (define/contract (denominations-of amount denominations)
      ;; split amount into units of denominations, returning the split
      ;; in descending order of denomination, and any remainder (if there is
      ;; no 1 denomination there will generally be a remainder).
      (-> natural-number/c (listof (integer-in 1 #f))
          (values (listof natural-number/c) natural-number/c))
      (let handle-one-denomination ([current amount]
                                    [remaining-denominations (sort denominations >)]
                                    [so-far '()])
        ;; handle a single denomination: current is the balance,
        ;; remaining-denominations is the denominations left (descending order)
        ;; so-far is the list of amounts of each denomination we've accumulated
        ;; so far, which is in ascending order of denomination
        (if (null? remaining-denominations)
            ;; we are done: return the reversed accumulator and anything left over
            (values (reverse so-far) current)
            (match-let ([(cons first-denomination rest-of-the-denominations)
                         remaining-denominations])
              (if (> first-denomination current)
                  ;; if the first denomination is more than the balance, just
                  ;; accumulate a 0 for it and loop on the rest
                  (handle-one-denomination current rest-of-the-denominations
                                           (cons 0 so-far))
                  ;; otherwise work out how much of it we need and how much is left
                  (let-values ([(q r)
                                (quotient/remainder current first-denomination)])
                    ;; and loop on the remainder accumulating the number of bills
                    ;; we needed
                    (handle-one-denomination r rest-of-the-denominations
                                             (cons q so-far))))))))
    

提交回复
热议问题