This commit is contained in:
Aleh Suprunovich 2024-12-03 00:27:50 +03:00
parent 17a3b8befb
commit a7b6626cae
3 changed files with 1061 additions and 0 deletions

1000
inputs/day2 Normal file

File diff suppressed because it is too large Load Diff

6
inputs/day2.example Normal file
View File

@ -0,0 +1,6 @@
7 6 4 2 1
1 2 7 8 9
9 7 6 2 1
1 3 2 4 5
8 6 4 4 1
1 3 6 7 9

55
src/day2.clj Normal file
View File

@ -0,0 +1,55 @@
(ns day2
(:require [clojure.string :as s]))
(defn line->vec [steps]
(->>
(re-seq #"\d+" steps)
(mapv parse-long)))
(def input
(->> "inputs/day2"
slurp
s/split-lines
(map line->vec)))
(defn diff [steps]
(->>
(partition 2 1 steps)
(map (partial apply -))))
(defn safe? [steps]
(let [diffs (diff steps)
sign (pos? (first diffs))]
(loop [diffs diffs]
(if (empty? diffs)
true
(if (zero? (first diffs))
false
(if-not (= sign (pos? (first diffs)))
false
(if (> (abs (first diffs)) 3)
false
(recur (rest diffs)))))))))
(defn cut-nth [steps n]
(concat (subvec steps 0 n)
(subvec steps (inc n))))
(defn safe?-2 [steps]
(if (safe? steps)
true
(not-empty
(for [i (range (count steps))
:let [safe (safe? (cut-nth steps i))]
:when (true? safe)]
safe))))
(println "Number of safe reports:"
(->> (map safe? input)
(filter true?)
count))
(println "Number of safe reports (part 2):"
(->> (map safe?-2 input)
(remove nil?)
count))