-
-
Save vanadium23/7423650bd1efdcbbbd8232e8f8d5e6f6 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(ns advent-of-code.day02 | |
(:require [clojure.string :as str] | |
[clojure.java.io :as io] | |
[clojure.math.combinatorics :as combo])) | |
(defn read-input [file] | |
(str/trim (slurp file))) | |
(defn to-lines | |
"Turn a blob or block into a seq of lines" | |
[input] | |
(str/split-lines input)) | |
(defn parse-line | |
"Parse a line into a seq of strings" | |
[line] | |
(map #(Integer/parseInt %) (str/split line #"\s+"))) | |
(defn safe-report [line] | |
(def asc true) | |
(def desc true) | |
(def levels true) | |
(doseq [[index b] (map-indexed vector (rest line))] | |
(let [a (nth line index) | |
diff (- b a)] | |
(if (< diff 0) | |
(def asc false)) | |
(if (> diff 0) | |
(def desc false)) | |
(if (= diff 0) | |
(def levels false)) | |
(if (> (abs diff) 3) | |
(def levels false)) | |
)) | |
(cond | |
(not levels) 0 | |
(and asc levels) 1 | |
(and desc levels) 1 | |
:else 0)) | |
(defn part1 [input] (reduce + (map safe-report (map parse-line (to-lines input))))) | |
(defn count-element [element lazy-seq] | |
(count (filter #(= % element) lazy-seq))) | |
(defn remove-each [line] | |
(map-indexed | |
(fn [idx _] | |
(concat (take idx line) (drop (inc idx) line))) | |
line)) | |
(defn safe-report2 [line] | |
;; (def safe (count-element 1 (map safe-report (combo/combinations line (dec (count line)))))) | |
(def safe (count-element 1 (map safe-report (remove-each line)))) | |
(if (= safe 0) 0 1)) | |
(defn part2 [input] (reduce + (map safe-report2 (map parse-line (to-lines input))))) | |
(def answer1example (part1 (read-input "02-example.txt"))) | |
(assert (= answer1example 2) answer1example) | |
(def answer1 (part1 (read-input "02.txt"))) | |
(assert (= answer1 218) answer1) | |
(def answer2example (part2 (read-input "02-example.txt"))) | |
(assert (= answer2example 4) answer2example) | |
(def answer2 (part2 (read-input "02.txt"))) | |
(assert (= answer2 290) answer2) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment