ref: master
2020/src/aoc/day09.clj
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 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 |
(ns aoc.day09 (:require [clojure.java.io :as io])) (def example "35 20 15 25 47 40 62 55 65 95 102 117 150 182 127 219 299 277 309 576") (defn valid? [n coll] (seq (for [x coll y coll :when (not= x y) :when (= n (+ x y))] [x y]))) (defn read-input [] (->> (io/resource "input09.txt") io/reader line-seq (map read-string))) (defn read-example-input [] (->> example clojure.string/split-lines (map read-string))) (defn compute-1 [input size] (loop [step 0] (let [without-old (drop step input) pool (take size without-old) candidate (nth without-old size)] (if-not (valid? candidate pool) candidate (recur (inc step)))))) (defn adds-up? [coll n] (loop [nums [] index 0] (cond (= (apply + nums) n) nums (> (apply + nums) n) nil :else (recur (conj nums (nth coll index)) (inc index))))) (defn find-range [input n] (loop [coll input] (let [r (adds-up? coll n)] (if-not (nil? r) r (recur (rest coll)))))) (defn compute-2 [input n] (let [result (find-range input n)] (+ (apply min result) (apply max result)))) (defn main [] (let [input (read-input) size 25 n (compute-1 input size)] (println n) (println (compute-2 input n)))) (main) |