about summary refs log tree commit diff
path: root/day07.clj
blob: be8d66b37d73bd47b06bd5eb54ca4d778ba791e3 (plain) (blame)
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
29
30
31
32
33
34
35
36
37
(ns org.vuxu.aoc2021.day07
  (:require [clojure.string :as str]))

(def data
  (->> (str/split (str/trim-newline (slurp "day07")) #",")
       (mapv parse-long)))

(defn median [coll]
  ; only works for even lengths but good enough here
  (nth (sort coll) (/ (count coll) 2)))

(defn integer-means [coll]
  (let [mean (/ (apply + coll) (count coll))]
    [(long (Math/floor mean))
     (long (Math/ceil mean))]))

(defn abs [n]
  (Math/abs n))

(defn fuel [n]
  (* 1/2 n (inc n)))

(def part1
  (->> data
       (map (partial - (median data)))
       (map abs)
       (apply +)))
;; => 328187

(def part2
  (apply min (for [m (integer-means data)]
               (->> data
                    (map (partial - m))
                    (map abs)
                    (map fuel)
                    (apply +)))))
;; => 91257582N