-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathday7.carth
18 lines (16 loc) · 886 Bytes
/
day7.carth
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
(import std)
(define main
(do io/bind
(<- input (io/map unwrap! (read-file "inputs/day7.txt")))
(let1 crabs (apps |> input
trim
(string/splits-on ",")
(map (<o unwrap! parse-int))
array/collect
(merge-sort num/cmp)))
(display (apps str-append "Part 1: " (show-int (total-fuel id (median crabs) crabs))))
(display (apps str-append "Part 2: " (show-int (total-fuel sum-nats-to-n (mean crabs) crabs))))))
(define (median sorted) (array/lookup! (/ (array/length sorted) (to-nat 2)) sorted))
(define (mean xs) (/ (+ (sum (array/iter xs)) 1) (to-int (array/length xs))))
(define (total-fuel f align crabs) (sum (map (apps <o f abs (- align)) (array/iter crabs))))
(define (sum-nats-to-n n) (/ (* n (+ 1 n)) 2)) ; Formula for sum of range [1,n]