Skip to content

Instantly share code, notes, and snippets.

@tatut
Created December 20, 2021 18:01
Show Gist options
  • Save tatut/1233cdcba52cb0b53659535bf975044f to your computer and use it in GitHub Desktop.
Save tatut/1233cdcba52cb0b53659535bf975044f to your computer and use it in GitHub Desktop.
(ns day20
(:require [clojure.java.io :as io]))
(def input (-> "day20.txt" io/reader line-seq))
(def enhance-alg (vec (first input)))
(def initial-img
(into #{}
(mapcat identity)
(map-indexed
(fn [y line]
(for [x (range (count line))
:when (= \# (.charAt line x))]
[x y]))
(drop 2 input))))
(defn bounds
"Return [minx miny maxx maxy] for img"
[img]
(let [xs (map first img)
ys (map second img)]
[(reduce min xs) (reduce min ys)
(reduce max xs) (reduce max ys)]))
(defn enhance [img out-lit]
(let [[minx miny maxx maxy] (bounds img)]
(letfn [(lit [[x y :as p]]
(if (and (<= minx x maxx)
(<= miny y maxy))
(if (img p) 1 0)
out-lit))
(grid-enhance-rule [x y]
(reduce #(bit-or (bit-shift-left %1 1) (lit %2)) 0
(for [dy [-1 0 1] dx [-1 0 1]] [(+ x dx) (+ y dy)])))]
(into #{}
(for [x (range (- minx 1) (+ maxx 2))
y (range (- miny 1) (+ maxy 2))
:when (= \# (enhance-alg (grid-enhance-rule x y)))]
[x y])))))
(defn part1 []
(-> initial-img
(enhance 0)
(enhance 1)
count))
(defn part2 []
(count
(reduce (fn [img out]
(enhance img out))
initial-img
(take 50 (cycle [0 1])))))
(time (part1)) ;; 77ms
(time (part2)) ;; 2520ms
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment