Skip to content

Instantly share code, notes, and snippets.

@ccann

ccann/day11.clj

Created Dec 11, 2018
Embed
What would you like to do?
AOC Day 11
(ns aoc.day11)
(def dim-x 300)
(def dim-y 300)
(defn make-grid
[]
(to-array-2d (repeat dim-x (repeat dim-y 0))))
(def serial-number 18)
(defn keep-hundreds
[n]
(if (< 99 n)
(Long. (str (nth (reverse (str n)) 2)))
0))
(defn power-level
[x y serial]
(let [rack-id (+ x 10)
power (-> (* rack-id y)
(+ serial)
(* rack-id)
(keep-hundreds)
(- 5))]
power))
(defn set-power-levels
[grid]
(doseq [x (range dim-x) y (range dim-y)]
(let [[-x -y] [(inc x) (inc y)]
power (power-level -x -y serial-number)]
(aset grid x y power))))
;; part 1 solve
(def master-grid (make-grid))
(set-power-levels master-grid)
(assert (= 4 (power-level 3 5 8)))
(assert (= -5 (power-level 122 79 57)))
(assert (= 0 (power-level 217 196 39)))
(assert (= 4 (power-level 101 153 71)))
;; part 2 solve
(defn square-power-levels
[grid size]
(println "size" size)
(let [pairs (transient [])]
(doseq [x (range dim-x)
y (range dim-y)]
(let [y-max (+ y size)
x-max (+ x size)
xs (vec (range x x-max))
ys (vec (range y y-max))]
(when (and (<= x-max dim-x) (<= y-max dim-y))
(let [lvls (transient [])]
(doseq [-x xs, -y ys]
(conj! lvls (aget grid -x -y)))
(conj! pairs [[(inc x) (inc y) size]
(reduce + (persistent! lvls))])))))
(persistent! pairs)))
(let [sizes (vec (range 2 301))
levels (mapv #(square-power-levels master-grid %) sizes)]
(sort-by second > (apply concat levels)))
(set! *unchecked-math* true)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment