day 2
This commit is contained in:
parent
a180f1d14c
commit
f91fe68f6b
52
src/day2.clj
Normal file
52
src/day2.clj
Normal file
@ -0,0 +1,52 @@
|
|||||||
|
(ns day2
|
||||||
|
(:require [clojure.edn :as edn]
|
||||||
|
[clojure.string :as string]
|
||||||
|
[helpers :refer [get-input]]))
|
||||||
|
|
||||||
|
|
||||||
|
(def test-input "11-22,95-115,998-1012,1188511880-1188511890,222220-222224,
|
||||||
|
1698522-1698528,446443-446449,38593856-38593862,565653-565659,
|
||||||
|
824824821-824824827,2121212118-2121212124")
|
||||||
|
|
||||||
|
(defn- gen-range [spec]
|
||||||
|
(let [[a b] (string/split (string/trim spec) #"-")
|
||||||
|
a (edn/read-string a)
|
||||||
|
b (inc (edn/read-string b))]
|
||||||
|
(map str (range a b))))
|
||||||
|
|
||||||
|
(defn- invalid? [id]
|
||||||
|
(let [c (count id)]
|
||||||
|
(and (even? c)
|
||||||
|
(let [first-half (apply str (take (/ c 2) id))]
|
||||||
|
(string/ends-with? id first-half)))))
|
||||||
|
|
||||||
|
;(def input (string/split test-input #","))
|
||||||
|
(def input (string/split (get-input 2) #","))
|
||||||
|
|
||||||
|
(println
|
||||||
|
"Sum of all invalid IDs:"
|
||||||
|
(->>
|
||||||
|
input
|
||||||
|
(mapcat gen-range)
|
||||||
|
(filter invalid?)
|
||||||
|
(map edn/read-string)
|
||||||
|
(reduce +)))
|
||||||
|
|
||||||
|
(defn- invalid?' [id]
|
||||||
|
(if (= 1 (count id))
|
||||||
|
false
|
||||||
|
(let [h (inc (/ (count id) 2))
|
||||||
|
make-ptn (fn [n]
|
||||||
|
(re-pattern
|
||||||
|
(str "(" (apply str (take n id)) ")+")))
|
||||||
|
patterns (map make-ptn (range 1 h))]
|
||||||
|
(some #(re-matches % id) patterns))))
|
||||||
|
|
||||||
|
(println
|
||||||
|
"Sum of all invalid IDs (part 2):"
|
||||||
|
(->>
|
||||||
|
input
|
||||||
|
(mapcat gen-range)
|
||||||
|
(filter invalid?')
|
||||||
|
(map edn/read-string)
|
||||||
|
(reduce +)))
|
||||||
Loading…
x
Reference in New Issue
Block a user