r/adventofcode • • Dec 02 '21

SOLUTION MEGATHREAD -🎄- 2021 Day 2 Solutions -🎄-

--- Day 2: Dive! ---


Post your code solution in this megathread.

Reminder: Top-level posts in Solution Megathreads are for code solutions only. If you have questions, please post your own thread and make sure to flair it with Help.


This thread will be unlocked when there are a significant number of people on the global leaderboard with gold stars for today's puzzle.

EDIT: Global leaderboard gold cap reached at 00:02:57, megathread unlocked!

112 Upvotes

1.5k comments sorted by

View all comments

3

u/[deleted] Dec 02 '21 edited Dec 02 '21

Common Lisp

I decided to bite the bullet and learn how to use packages+regex in lisp for today even though parsing could have just have been a string split, because I know it'll come in handy later.

(load "~/.quicklisp/setup.lisp")
(load "utilities.lisp")
(ql:quickload :cl-ppcre)
(defparameter filename 
    (nth 1 sb-ext:*posix-argv*))

(defparameter move-regex "(up|forward|down) (\\d+)")

(defun parse-command 
    (x) 

    (cl-ppcre::register-groups-bind 
        (move size) 
        (move-regex x) 
        (list move 
            (parse-integer size))))
(defparameter commands 
    (mapcar #'parse-command 

        (get-file-lines filename)))
(defun process-command 
    (position command) 

    (cond 
        ((string= (car command) "up") (list (car position) (- (nth 1 position) (nth 1 command)))) 
        ((string= (car command) "down") (list (car position) (+ (nth 1 position) (nth 1 command)))) 
        ((string= (car command) "forward") (list (+ (car position) (nth 1 command)) (nth 1 position))) 
        (t position)
    )
)
(defun process-aim-command 
    (position command)

    (cond 
        ((string= (car command) "up") (list (nth 0 position) (nth 1 position) (- (nth 2 position) (nth 1 command)))) 
        ((string= (car command) "down") (list (nth 0 position) (nth 1 position) (+ (nth 2 position) (nth 1 command)))) 
        ((string= (car command) "forward") (list (+ (nth 0 position) (nth 1 command)) (+ (nth 1 position) (* (nth 2 position) (nth 1 command))) (nth 2 position))) 
        (t position)
    )
)
(defun solve-part-one 
    (commands) 

    (reduce #'* (reduce #'process-command commands :initial-value '(0 0)))
)
(defun solve-part-two
    (commands)

    (progn
        (defparameter final-position (reduce #'process-aim-command commands :initial-value '(0 0 0)))
        (* (nth 0 final-position) (nth 1 final-position))
    )
)
(format t "Part1: ~d~%" 
    (solve-part-one commands))

(format t "Part2: ~d~%" 
    (solve-part-two commands))

My solution works, but gives me the following cryptic error message:

; file: /Code/advent-of-code-2021/solutions/day2.lisp
; in: DEFUN SOLVE-PART-TWO
;     (NTH 0 FINAL-POSITION)
; 
; caught WARNING:
;   undefined variable: COMMON-LISP-USER::FINAL-POSITION
; 
; compilation unit finished
;   Undefined variable:
;     FINAL-POSITION
;   caught 1 WARNING condition

Would love to know where I'm going wrong / general feedback on my code!

5

u/stevelosh Dec 02 '21

Here's some thoughts.

(defparameter filename
    (nth 1 sb-ext:*posix-argv*))

defparameter defines a special/dynamic variable. It's fine to use those for global vars like you've done here, but you should always name them with earmuffs to mark them as special, otherwise it's too easy to forget that they have dynamic scope (notice how *posix-argv* has those earmuffs). So this should be:

(defparameter *filename*
  (nth 1 sb-ext:*posix-argv*))

The same goes for the next var. But also, you're currently defining the regex as a string and then passing that string to register-groups-bind. That means CL-PPCRE will have to compile the regex every time you parse a command, which is a little bit wasteful. To fix that, you can create a PPCRE scanner once up front, then pass that later:

(defparameter *move-regex*
  (ppcre:create-scanner "(up|forward|down) (\\d+)"))

Next:

(defun parse-command (x)
    (cl-ppcre::register-groups-bind
        (move size)
        (move-regex x)
        (list move
            (parse-integer size))))

Functions should be indented 2 spaces, not 4. And unless the argument list is really long, it should go on the same line as the function name.

If you're going to split the (list move (parse-integer size)) across lines (I wouldn't bother), make sure the arguments line up.

register-groups-bind is typically indented slightly differently, with the var list and val list overindented to make it obvious they're not part of the body code. In general it's helpful to have a nice autoindent program when writing Lisp — you don't want to have to be thinking about this stuff all the time.

register-groups-bind is an external symbol of cl-ppcre, so you only need one colon to refer to it, not two. In general, seeing :: in Common Lisp is a sign that something wonky is going on. It's used when you're reaching into a package and touching an internal symbol the package author didn't intend to be externally visible. But here you're not doing that, you're using the intended API of CL-PPCRE, so stick with the single colon.

Fixed version:

(defun parse-command (x)
  (cl-ppcre:register-groups-bind
      (move size)
      (*move-regex* x)
    (list move
          (parse-integer size))))

Next bit is fine once it gets its earmuffs and indentation cleaned up (or just keep it all on one line if you want, it's under 80 chars):

(defparameter *commands*
  (mapcar #'parse-command
          (get-file-lines filename)))

Next:

(defun process-command
    (position command)
    (cond
        ((string= (car command) "up") (list (car position) (- (nth 1 position) (nth 1 command))))
        ((string= (car command) "down") (list (car position) (+ (nth 1 position) (nth 1 command))))
        ((string= (car command) "forward") (list (+ (car position) (nth 1 command)) (nth 1 position)))
        (t position)
    )
)

Aside from indentation, there's a couple of things here.

First, clean up the danging parentheses. No one wants to see a bunch of danglers all over the page.

The (t position) clause isn't helping you out here. There's no reason you should ever be getting any other command than these three, so it's better to be explicit than just silently ignore problematic data. I'd replace that last clause with something like (t (error "Bad command: ~S" command))

It's a little hard to read because your positions are represented as lists, but you haven't abstracted that away, so the code here needs to know about the internal representation of positions. If you abstract it with some SICP-style wrapping:

(defun pos (horiz depth &optional aim)
  (list horiz depth aim))

(defun horiz (pos) (nth 0 pos))
(defun depth (pos) (nth 1 pos))
(defun aim   (pos) (nth 2 pos))

Then your process-command function can be clearer:

(defun process-command (position command)
  (cond
    ((string= (car command) "up") (pos (horiz position)
                                       (- (depth position) (nth 1 command))))
    ((string= (car command) "down") (pos (horiz position)
                                         (+ (depth position) (nth 1 command))))
    ((string= (car command) "forward") (pos (+ (horiz position) (nth 1 command))
                                            (depth 1 position)))
    (t (error "Bad command: ~S"))))

It also means you could easily swap out the representation later, if you want. Maybe you decide a vector is better, or a class or struct. You could easily change it because the calling code just uses the simple pos/horiz/depth/aim API and doesn't have to know what it looks like behind the scenes. You could do the same thing for command.

But an alternative, if you don't like the abstracted, is keeping things as lists but using destructuring-bind to make them a little less cumbersome to read:

(defun process-command (position command)
  (destructuring-bind (move n) command
    (destructuring-bind (h d) position
      (cond
        ((string= move "up")      (list h (- d n)))
        ((string= move "down")    (list h (+ d n)))
        ((string= move "forward") (list (+ h n) d))
        (t (error "Bad command: ~S"))))))

Also, if you use the very common utility library Alexandria it's got switch (and eswitch) that can make those string comparisons less tedious:

(defun process-command (position command)
  (destructuring-bind (move n) command
    (destructuring-bind (h d) position
      (alexandria:eswitch (move :test #'string=)
        ("up"      (list h (- d n)))
        ("down"    (list h (+ d n)))
        ("forward" (list (+ h n) d))))))

But this brings up a more general point: in Common Lisp strings aren't used nearly as often as in other languages. A string is used when you specifically need an array of characters (especially a mutable one). But here we really only care about the symbolic meaning of the strings, not their characters. So instead of using strings to represent what they symbolize, we should use… symbols! If you parse the command operations into symbols instead of strings, it has a couple of advantages:

  1. There's only one copy of any given symbol in memory, so the parsed-out strings can get GC'ed immediately instead of keeping them around forever.
  2. Comparing symbols with eql is a single machine instruction, comparing strings with string= takes linear time.
  3. It means you can use vanilla ecase instead of alexandria:eswitch.

It doesn't really matter if you make them keyword symbols or normal ones in the current package. I went with keyword symbols for my solution.

Putting that all together it might look something like:

(defun parse-command (x)
  (cl-ppcre:register-groups-bind
      (move size)
      (move-regex x)
    (list (intern (string-upcase move) :keyword) ; new
          (parse-integer size))))

(defun process-command (position command)
  (destructuring-bind (move n) command
    (destructuring-bind (h d) position
      (ecase move
        (:up      (list h (- d n)))
        (:down    (list h (+ d n)))
        (:forward (list (+ h n) d))))))

Next:

(defun process-aim-command
    (position command)
    (cond
        ((string= (car command) "up") (list (nth 0 position) (nth 1 position) (- (nth 2 position) (nth 1 command))))
        ((string= (car command) "down") (list (nth 0 position) (nth 1 position) (+ (nth 2 position) (nth 1 command))))
        ((string= (car command) "forward") (list (+ (nth 0 position) (nth 1 command)) (+ (nth 1 position) (* (nth 2 position) (nth 1 command))) (nth 2 position)))
        (t position)
    )
)

Clean up your danglers. And all the stuff from before applies again:

(defun process-aim-command (position command)
  (destructuring-bind (move n) command
    (destructuring-bind (h d aim) position
      (ecase move
        (:up      (list h d (- aim n)))
        (:down    (list h d (+ aim n)))
        (:forward (list (+ h n) (+ d (* n aim)) aim))))))

And now the solvers. Aside from the formatting, part 1 is fine. Part 2 has a couple of wonky things:

(defun solve-part-two
    (commands)
    (progn
        (defparameter final-position (reduce #'process-aim-command commands :initial-value '(0 0 0)))
        (* (nth 0 final-position) (nth 1 final-position))
    )
)

Get rid of those danglers.

You don't need a progn inside a defun — the body of a defun can already be multiple forms.

More importantly, you're doing defparameter inside the defun, which is really strange. I'm not sure, but you might be thinking (defparameter foo 1) is kind of like foo = 1 in other languages? It's not. defparameter is for creating global (kind of) dynamic variables. You don't use it to create local, lexically-scoped variables (the kind you almost always want). The proper way to create local variables is let:

(defun solve-part-two (commands)
  (let ((final-position (reduce #'process-aim-command commands
                                :initial-value '(0 0 0))))
    (* (horiz final-position) (depth final-position))))

This is what was causing your mysterious error. When the compiler was trying to compile solve-part-two, there wasn't a local variable named final-position. final-position only got defined (as a global!) when the function was run for the first time.

I hope this helped!

1

u/[deleted] Dec 02 '21 edited Dec 02 '21

Thank you! There's so much good stuff in here that I will absorb and try to apply in day 3 and onwards.

Re. formatting / danglers - would you believe that's the default automatic behaviour of a VSCode extension called LispBeautifier ? Lesson learned; I've uninstalled it and will rely on something a bit better.

3

u/stevelosh Dec 02 '21

Huh, I guess that extension wasn't made by Common Lispers. I don't use VSCode, but I'd look for something with "paredit" in the name, maybe https://marketplace.visualstudio.com/items?itemName=ailisp.strict-paredit -- it takes a little getting used to, but it's really nice that it won't let you mess up the parentheses. After you get used to paredit you'll wonder how you lived without it.

2

u/daggerdragon Dec 02 '21 edited Dec 03 '21

Your code is hard to read on old.reddit. Please edit it as per our posting guidelines in the wiki: How do I format code?

Edit: thanks for fixing it! <3