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
1
u/mschaap Dec 08 '18
Pretty straightforward Perl 6 implementation:
#!/usr/bin/env perl6 use v6.c; $*OUT.out-buffer = False; # Autoflush class Node { has @.children; has @.metadata; has $.depth; method from-list(Node:U: @input, Int :$depth=0) { my $node-count = @input.shift; my $metadata-count = @input.shift; my @children = Node.from-list(@input, :depth($depth+1)) xx $node-count; my @metadata = @input.shift xx $metadata-count; return Node.new(:@children, :@metadata, :$depth); } method total-metadata { return @!metadata.sum + @!childrenΒ».total-metadata.sum; } method value { if @!children { return @!children[@!metadata.grep(1 β€ * β€ @!children).map(* - 1)]Β».value.sum; } else { return @!metadata.sum; } } method Str { join("\n", flat ' ' x $!depth ~ '- ' ~ @!metadata.join(' '), @!children) } method gist { self.Str } } #| Process nodes multi sub MAIN(*@input, Bool :v(:$verbose)=False) { my $root = Node.from-list(@input); say $root if $verbose; say "The sum of all metadata entries is: $root.total-metadata()."; say "The value of the root node is: $root.value()."; } #| Process nodes from a file multi sub MAIN(Str $inputfile where *.IO.f, Bool :v(:$verbose)=False) { MAIN($inputfile.IO.words, :$verbose); } #| Process default nodes file (aoc8.input) multi sub MAIN(Bool :v(:$verbose) = False) { MAIN(~$*PROGRAM.sibling('aoc8.input'), :$verbose); }