AoC'21, day 7, second problem rvc


Same as the first problem, except now the fuel burn rate is G(d), where d is the (always positive) distance traveled and G is the Gaussian sum 1 + 2 + ... + d.

 $ cat 07b.rkt  
 #lang racket 
  
  
 (require 
   (prefix-in aoc7: "07a.rkt") 
   ) 
  
  
 (define (aoc07b . args) 
  
   ; Return the most fuel-efficient meeting point for the given 
   ; crab navy positions.  If no positions are given, use the 
   ; contest problem input; otherwise assume the argument is the 
   ; string representation of a problem input. 
  
   (cheapest-crab-fleet-fuel-burn (apply aoc7:read-input args))) 
  
  
 (define (cheapest-crab-fleet-fuel-burn positions) 
  
   ; Return the minimum amount of fuel needed for the crab navy at 
   ; the given positions to rendezvous at some point. 
  
   (let* 
  
     ((mn (apply min positions)) 
      (mx (apply max positions)) 
  
      (delta-fuel-used (lambda (d) (/ (* d (+ d 1)) 2))) 
  
      (total-fuel-used 
        (lambda (pt) 
          (foldl 
            (lambda (sp fu) 
              (+ fu (delta-fuel-used (abs (- sp pt))))) 
            0 positions)))) 
  
     (let loop 
  
       ((p mn) 
        (min-f (* (delta-fuel-used mx) (length positions)))) 
  
       (if (> p mx) 
         min-f 
         (loop (+ p 1) (min (total-fuel-used p) min-f)))))) 
  
  
 (define example-result 168) 
  
  
 (module+ main 
   (aoc07b) 
   ) 
  
  
 (module+ test 
  
   (require rackunit) 
  
   (check-equal? 
     (cheapest-crab-fleet-fuel-burn 
       (aoc7:read-input aoc7:example-data)) 
     example-result) 
  
   (check-equal? (aoc07b) 92881128) 
   ) 
  
 $ raco test 07b.rkt  
 raco test: (submod "07b.rkt" test) 
 2 tests passed 
  
 $