aboutsummaryrefslogtreecommitdiff
path: root/racket/aoc2021/day-07/day-07.rkt
blob: 89d5009c8301bce3d421d5c6c163d687ca5afff6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#lang racket
(require advent-of-code
         threading
         math/statistics)

(define crab-data
  (~> (open-aoc-input (find-session) 2021 7 #:cache #t)
      port->string
      string-trim
      (string-split ",")
      (map string->number _)))

(define (gauss-sum n)
  (/ (* n (+ n 1)) 2))
(define (compute-fuel-use f crabs align-to)
  (for/sum ([crab (in-list crabs)]) (f (abs (- crab align-to)))))

;; using the fact that the optimum location is at the median
;; of the crabs' starting location for the linear relationship
;; and at a coordinate within 1 unit of the mean for the quadratic one

(~>> crab-data (median <) (compute-fuel-use identity crab-data))

(~>> crab-data
     mean
     ((λ (m) (list (floor m) (ceiling m))))
     (map (curry compute-fuel-use gauss-sum crab-data))
     (apply min))