Created
December 2, 2018 15:01
-
-
Save death/ed5a8ac5b2500122781107e845c40200 to your computer and use it in GitHub Desktop.
Advent of Code 2017 - Day 3
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
;;;; +----------------------------------------------------------------+ | |
;;;; | Advent of Code 2017 | | |
;;;; +----------------------------------------------------------------+ | |
(defpackage #:snippets/aoc2017/day3 | |
(:use #:cl) | |
(:export | |
#:day3)) | |
(in-package #:snippets/aoc2017/day3) | |
(defun spiral (function) | |
(catch 'stop | |
(let ((c 1) | |
(v 0) | |
(x 0) | |
(y 0)) | |
(flet ((visit (dx dy) | |
(incf x dx) | |
(incf y dy) | |
(incf v) | |
(funcall function x y v))) | |
(visit 0 0) | |
(loop | |
(visit 1 0) | |
(dotimes (i c) | |
(visit 0 -1)) | |
(dotimes (i (+ 1 c)) | |
(visit -1 0)) | |
(dotimes (i (+ 1 c)) | |
(visit 0 1)) | |
(dotimes (i (+ 1 c)) | |
(visit 1 0)) | |
(incf c 2)))))) | |
(defun run-spiral (upper) | |
(spiral | |
(lambda (x y v) | |
(when (= v upper) | |
(throw 'stop (list x y)))))) | |
(defun distance (value) | |
(destructuring-bind (x y) (run-spiral value) | |
(+ (abs x) (abs y)))) | |
(defun neighbors-sum (test-value) | |
(let ((grid (make-hash-table :test 'equal))) | |
(macrolet ((cell (x y) | |
`(gethash (list ,x ,y) grid 0))) | |
(spiral | |
(lambda (x y v) | |
(declare (ignore v)) | |
(setf (cell x y) | |
(if (and (zerop x) (zerop y)) | |
1 | |
(+ (cell (- x 1) (- y 1)) | |
(cell (- x 1) y) | |
(cell (- x 1) (1+ y)) | |
(cell x (- y 1)) | |
(cell x (+ y 1)) | |
(cell (+ x 1) (- y 1)) | |
(cell (+ x 1) y) | |
(cell (+ x 1) (+ y 1))))) | |
(when (> (cell x y) test-value) | |
(throw 'stop (cell x y)))))))) | |
(defun day3 (input-value) | |
(list (distance input-value) | |
(neighbors-sum input-value))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment