diff options
Diffstat (limited to 'year2021/day7')
-rw-r--r-- | year2021/day7/maxima.mac | 10 | ||||
-rw-r--r-- | year2021/day7/part1.clj | 18 | ||||
-rw-r--r-- | year2021/day7/part2.clj | 20 |
3 files changed, 48 insertions, 0 deletions
diff --git a/year2021/day7/maxima.mac b/year2021/day7/maxima.mac new file mode 100644 index 0000000..a1c2d18 --- /dev/null +++ b/year2021/day7/maxima.mac @@ -0,0 +1,10 @@ +load("descriptive")$ +load("in.mac")$ /* Should define `input` list of numbers. */ + +calcfuel(pos, distmod) := + lreduce("+", map(lambda([n], distmod(abs(pos - n))), input))$ + +calcfuel(median(input), lambda([x],x)); +calcfuel(floor(mean(input)), lambda([x], (x*(x+1)/2))); +calcfuel(floor(mean(input)) + 1, lambda([x], (x*(x+1)/2))); + diff --git a/year2021/day7/part1.clj b/year2021/day7/part1.clj new file mode 100644 index 0000000..f08e5b4 --- /dev/null +++ b/year2021/day7/part1.clj @@ -0,0 +1,18 @@ +(defn median [lst] + (as-> (count lst) $ + (quot $ 2) + (subvec (vec (sort lst)) (dec $) (inc $)) + (if (even? (count lst)) (apply + $) (second $)) + (quot $ 2) + ) + ) + +(as-> (slurp "./in") $ ; "16,1,2,0,4,2,7,1,2,14" + (clojure.string/split $ #",") + (mapv read-string $) + (map (partial - (median $)) $) + (map #(Math/abs %) $) + (apply + $) + (println $) + ) + diff --git a/year2021/day7/part2.clj b/year2021/day7/part2.clj new file mode 100644 index 0000000..b96b55d --- /dev/null +++ b/year2021/day7/part2.clj @@ -0,0 +1,20 @@ +(defn calc-fuel [lst pos] + (reduce #(as-> %2 $ + (- pos $) + (Math/abs $) + (/ (* $ (inc $)) 2) + (+ %1 $) + ) + 0 lst + ) + ) + +(let [input (as-> (slurp "./in") $ ;"16,1,2,0,4,2,7,1,2,14" + (clojure.string/split $ #",") + (map read-string $) + ) + mean (quot (apply + input) (count input))] + (println (min (calc-fuel input mean) + (calc-fuel input (inc mean)))) + ) + |