Day 6, Part 2

This commit is contained in:
Correl Roush 2015-12-14 12:40:00 -05:00
parent b54ff7b5e6
commit 90076448b4

View file

@ -3086,4 +3086,90 @@ After following the instructions, how many lights are lit?
#+RESULTS[2e528f53a45a3c7e0dcc549d5ac69918287ddd6e]: #+RESULTS[2e528f53a45a3c7e0dcc549d5ac69918287ddd6e]:
: 377891 : 377891
** Part 2
You just finish implementing your winning light pattern when you
realize you mistranslated Santa's message from Ancient Nordic Elvish.
The light grid you bought actually has individual brightness controls;
each light can have a brightness of zero or more. The lights all start
at zero.
The phrase =turn on= actually means that you should increase the
brightness of those lights by =1=.
The phrase =turn off= actually means that you should decrease the
brightness of those lights by =1=, to a minimum of zero.
The phrase =toggle= actually means that you should increase the
brightness of those lights by =2=.
What is the total brightness of all lights combined after following
Santa's instructions?
For example:
- =turn on 0,0 through 0,0= would increase the total brightness by
=1=.
- =toggle 0,0 through 999,999= would increase the total brightness by
=2000000=.
----------------------------------------------------------------------
#+BEGIN_SRC emacs-lisp :var input=6-input :exports both
(defun day6.2/make-light ()
0)
(defun day6.2/turn-on-light (light)
(+ 1 light))
(defun day6.2/turn-off-light (light)
(if (>= 0 light) 0
(- light 1)))
(defun day6.2/toggle-light (light)
(+ 2 light))
(defun day6.2/parse-instruction (instruction)
(if (string-match (concat "\\(turn \\(on\\|off\\)\\|toggle\\) "
"\\([0-9]+\\),\\([0-9]+\\)"
" through "
"\\([0-9]+\\),\\([0-9]+\\)")
instruction)
(list (cond ((string-equal "turn on" (match-string 1 instruction))
#'day6.2/turn-on-light)
((string-equal "turn off" (match-string 1 instruction))
#'day6.2/turn-off-light)
((string-equal "toggle" (match-string 1 instruction))
#'day6.2/toggle-light))
(string-to-int (match-string 3 instruction))
(string-to-int (match-string 4 instruction))
(string-to-int (match-string 5 instruction))
(string-to-int (match-string 6 instruction)))))
(defun day6.2/run-instruction (grid instruction)
(let ((parsed-instruction (day6.2/parse-instruction instruction)))
(eval (append '(day6/change-range grid)
`(',(first parsed-instruction))
(rest parsed-instruction)))))
(defun day6.2/make-grid (size)
(let ((table (make-hash-table :size (* size size))))
(-each (number-sequence 0 (- (* size size) 1))
(lambda (pos) (puthash pos (day6.2/make-light) table)))
(cons size
table)))
(defun day6.2/total-brightness (grid)
(-reduce #'+
(day6/grid-lights grid)))
(let ((grid (day6.2/make-grid 1000)))
(-each (split-string input "\n" t)
(apply-partially 'day6.2/run-instruction grid))
(day6.2/total-brightness grid))
#+END_SRC
#+RESULTS[ceaf378dab9cbe4211307b258b4fe66d2a04482b]:
: 14110788