112
SOLUTION MEGATHREAD-🎄- 2021 Day 2 Solutions -🎄-(self.adventofcode)
submitted 4 years, 1 month ago* (edited 4 minutes after) by daggerdragon to /r/adventofcode (134.8k)
--- Day 2: Dive! ---
Post your code solution in this megathread.
- Include what language(s)...
since 4 years, 1 month ago
5 of 5
Tip Reveddit Real-Time can notify you when your content is removed.
your account history
Tip Check if your account has any removed comments.
view my removed comments you are viewing a single comment's thread.
view all comments


Common Lisp
This is slightly cleaned up from my initial version, in particular reading the input was simplified to just use Common Lisp's
readfunction. I was reading each line, initially, splitting them, and then had more complex conditional logic.readmostly does what you want, most alphanumeric (+ some symbols) strings become symbols, numbers become numbers.loopdoes a destructuring bind when you usein. If you just want a single element then you'll do (with some typed in values, expect typos, not actually executed in a REPL):For a more complex structure (in this case I'll imitate my directions list):
Instead of getting those values and having to break them out later, I just used destructuring bind to get both parts:
The destructuring bind is the same (or at least equivalent) as with the actual special form
destructuring-bind:But it's wrapped up in the
loopstructure itself so I don't have to either do it myself later or use accessors (likefirst/carorsecond/cadr) which would make the rest of it uglier (in my opinion, especially how oftendistis used).readwill parse strings that are alphanumeric (and some other symbols, whatever is acceptable for an actual Lisp symbol likefoo-baror*earmuffs*) as symbols, and strings that are numeric (depending on the value of*read-base*, defaults to 10) as numbers. So I did this:The
niltellsreadnot to signal an error when it reaches the end of file, instead we just getnilas the result of a read (coincidence, not because that's the value given there). That's why I have thewhileloop there, when either of those turn up with nil (should the input be malformed and not have an even number of inputs). So I do two reads in succession, and collect the results into a new list (could've used a cons or a struct or anything else appropriate).That loop could also be used to solve the problem in a single pass since we don't actually need the input, but I like to keep the reading and the processing separated.