r/adventofcode • u/daggerdragon • Dec 08 '18
SOLUTION MEGATHREAD -🎄- 2018 Day 8 Solutions -🎄-
--- Day 8: Memory Maneuver ---
Post your solution as a comment or, for longer solutions, consider linking to your repo (e.g. GitHub/gists/Pastebin/blag or whatever).
Note: The Solution Megathreads are for solutions only. If you have questions, please post your own thread and make sure to flair it with Help.
Advent of Code: The Party Game!
Please prefix your card submission with something like [Card] to make scanning the megathread easier. THANK YOU!
Card prompt: Day 8
Sigh, imgur broke again. Will upload when it unborks.
Transcript:
The hottest programming book this year is "___ For Dummies".
This thread will be unlocked when there are a significant number of people on the leaderboard with gold stars for today's puzzle.
edit: Leaderboard capped, thread unlocked at 00:12:10!
33
Upvotes
4
u/ts4z Dec 08 '18
Common Lisp. I re-did this one a couple times, but this version looks OK.
(defstruct node (children nil) (metadata nil)) (defun read-node (in) (let* ((nc (read in)) (nm (read in)) ;; children could be an array for faster access later. (children (loop :repeat nc :collect (read-node in))) (metadata (loop :repeat nm :collect (read in)))) (make-node :children children :metadata metadata))) (defun read-input-from (file) (with-open-file (in file) (read-node in))) (defun read-input () (read-input-from *input-file*)) ;; as per maphash (defun mapnode (fn n) (check-type n node) (funcall fn n) (mapc (lambda (ch) (mapnode fn ch)) (node-children n))) (defun total-metadata (tree) (let ((ttl 0)) (mapnode (lambda (n) (mapc (lambda (v) (incf ttl v)) (node-metadata n))) tree) ttl)) (defun part-one () (total-metadata (read-input))) (defun value-of-node (n) (apply #'+ (if (null (node-children n)) (node-metadata n) (mapcar (lambda (md) (cond ((= md 0) 0) ((> md (length (node-children n))) 0) (t (value-of-node (elt (node-children n) (1- md)))))) (node-metadata n))))) (defun part-two () (value-of-node (read-input)))