Skip to content

Instantly share code, notes, and snippets.

@gsinclair
Created February 9, 2022 11:09
Show Gist options
  • Save gsinclair/ab33414f3ff5beaabdceb66dfe3d7915 to your computer and use it in GitHub Desktop.
Save gsinclair/ab33414f3ff5beaabdceb66dfe3d7915 to your computer and use it in GitHub Desktop.
;; Problem 13 from Advent of Code 2021 -- origami
(defn fold-left [fold-x [x y :as point]]
(if (< x fold-x)
point
[(- (* 2 fold-x) x) y]))
(defn fold-up [fold-y [x y :as point]]
(if (< y fold-y)
point
[x (- (* 2 fold-y) y)]))
(defn parse-13 [text]
(let [[part1 part2] (gs-paragraphs text)
points (->> (re-seq #"\d+" part1)
(map parse-long)
(partition 2)
(map vec))
functions (for [match (re-seq #"([xy])=(\d+)" part2)
:let [[_ xy n] match
n (parse-long n)]]
(case xy
"x" (partial fold-left n)
"y" (partial fold-up n)))]
[points functions]))
(defn p13a
"How many dots are visible after completing the first fold?"
[text]
(let [[points transforms] (parse-13 text)]
(->> points
(map (first transforms))
set
count)))
(comment
(e.g. (p13a input/p13-test) --> 17
(p13a input/p13-data) --> 17))
(defn print-points [points]
; Need to know the size of the canvas, and make a set of the points so we
; can do fast lookups.
(let [points (set points)
X (->> points (map first) (apply max))
Y (->> points (map second) (apply max))]
(doseq [y (range (inc Y))]
(doseq [x (range (inc X))]
(if (contains? points [x y])
(print "#")
(print " ")))
(print "\n"))))
(defn p13b
"Apply all transformations and print the resulting dot pattern so
so that eight capital letters can be discerned."
[text]
(let [[points transforms] (parse-13 text)
transform (apply comp (reverse transforms))
points' (->> points
(map transform)
set)]
(print-points points')))
(comment
(p13b input/p13-test)
(p13b input/p13-data))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment