Skip to content

Instantly share code, notes, and snippets.

@felideon
Last active December 4, 2016 06:56
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 felideon/1f82a10864106e2ce7bb49176277573d to your computer and use it in GitHub Desktop.
Save felideon/1f82a10864106e2ce7bb49176277573d to your computer and use it in GitHub Desktop.
Solution for http://adventofcode.com/2016/day/2 in Common Lisp
(in-package #:cl-advent-2016)
(defparameter *keypad* nil)
(defparameter *key* 5)
(defun key-position ()
(mapcar (lambda (row) (position *key* row)) *keypad*))
(defun row-index ()
(position-if-not #'null (key-position)))
(defun col-index ()
(some #'identity (key-position)))
(defun row ()
(nth (row-index) *keypad*))
(defun row-above ()
(when (plusp (row-index))
(nth (1- (row-index)) *keypad*)))
(defun row-below ()
(unless (= (length *keypad*) (1- (row-index)))
(nth (1+ (row-index)) *keypad*)))
(defun key-up ()
(nth (col-index) (row-above)))
(defun key-down ()
(nth (col-index) (row-below)))
(defun key-left ()
(when (plusp (col-index))
(nth (1- (col-index)) (row))))
(defun key-right ()
(unless (= (length (row)) (1- (col-index)))
(nth (1+ (col-index)) (row))))
(defun edgep (direction)
(cond ((eq direction :up) (null (key-up)))
((eq direction :down) (null (key-down)))
((eq direction :left) (null (key-left)))
((eq direction :right) (null (key-right)))
(t (break "~s is an uknown direction" direction))))
(defun up ()
(if (edgep :up)
*key*
(setf *key* (key-up))))
(defun down ()
(if (edgep :down)
*key*
(setf *key* (key-down))))
(defun left ()
(if (edgep :left)
*key*
(setf *key* (key-left))))
(defun right ()
(if (edgep :right)
*key*
(setf *key* (key-right))))
(defun run-instruction (str)
(cond ((string-equal str "U") (up))
((string-equal str "D") (down))
((string-equal str "L") (left))
((string-equal str "R") (right))
(t nil)))
(defun run-instructions (str)
(loop for line in (split-sequence #\Newline str)
do (loop for c across line do (run-instruction (string c)))
when (plusp (length line))
collect *key*))
(defun keypad-1 ()
(let ((*keypad* '((1 2 3)
(4 5 6)
(7 8 9))))
(run-instructions
(alexandria:read-file-into-string #p"keypad-instructions.txt"))))
(defun keypad-2 ()
(let ((*keypad* '((nil nil 1 nil nil)
(nil 2 3 4 nil)
(5 6 7 8 9)
(nil A B C nil)
(nil nil D nil nil))))
(run-instructions
(alexandria:read-file-into-string #p"keypad-instructions.txt"))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment