Skip to content

Instantly share code, notes, and snippets.

@Rogach
Created December 8, 2018 07:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Rogach/4f2366bfa300042b85b0ebaeb066a823 to your computer and use it in GitHub Desktop.
Save Rogach/4f2366bfa300042b85b0ebaeb066a823 to your computer and use it in GitHub Desktop.
;; input is from https://adventofcode.com/2015/day/6
(def W 1000)
(def input (clojure.string/split-lines (slurp "d06.txt")))
(defmacro control-lights [lights x1 y1 x2 y2 f]
(let [i (gensym)]
`(doseq [ x# (range ~x1 (inc ~x2))
y# (range ~y1 (inc ~y2))
:let [ ~i (+ (* y# W) x#) ] ]
(aset ~lights ~i
~(eval `(~f '(aget ~lights ~i)))))))
(time
(printf "unreadable macro: %d\n"
(let [lights (boolean-array (* W W))]
(doseq [s input]
(let [ m (re-matches #"(turn on|turn off|toggle) (\d+),(\d+) through (\d+),(\d+)" s)
command (get m 1)
x1 (Integer/parseInt (get m 2))
y1 (Integer/parseInt (get m 3))
x2 (Integer/parseInt (get m 4))
y2 (Integer/parseInt (get m 5)) ]
(cond
(= command "turn on") (control-lights lights x1 y1 x2 y2 (fn [v] `true))
(= command "turn off") (control-lights lights x1 y1 x2 y2 (fn [v] `false))
(= command "toggle") (control-lights lights x1 y1 x2 y2 (fn [v] `(not ~v)))
)))
(count (filter identity lights)))))
(time
(printf "clean code: %d\n"
(let [lights (boolean-array (* W W))]
(doseq [s input]
(println s)
(let [ m (re-matches #"(turn on|turn off|toggle) (\d+),(\d+) through (\d+),(\d+)" s)
command (get m 1)
compute (case command
"turn on" (constantly true)
"turn off" (constantly false)
"toggle" not)
x1 (Integer/parseInt (get m 2))
y1 (Integer/parseInt (get m 3))
x2 (Integer/parseInt (get m 4))
y2 (Integer/parseInt (get m 5)) ]
(doseq [ x (range x1 (inc x2))
y (range y1 (inc y2))
:let [i (+ (* y W) x)] ]
(aset lights i (compute (aget lights i))))
))
(count (filter identity lights)))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment