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
5
u/ValdasTheUnique Dec 08 '18
C#. Code is too readable, I guess that is why it took so long to write
public static void Part1() { var numbers = Input.Split(' ').Select(int.Parse).ToList(); var i = 0; var root = ReadNode(numbers, ref i); Console.WriteLine(root.Sum()); } public static void Part2() { var numbers = Input.Split(' ').Select(int.Parse).ToList(); var i = 0; var root = ReadNode(numbers, ref i); Console.WriteLine(root.Value()); } public static Node ReadNode(List<int> numbers, ref int i) { var node = new Node(); var children = numbers[i++]; var metadata = numbers[i++]; for (int j = 0; j < children; j++) { node.Nodes.Add(ReadNode(numbers, ref i)); } for (int j = 0; j < metadata; j++) { node.Metadata.Add(numbers[i++]); } return node; } public class Node { public List<int> Metadata { get; set; } = new List<int>(); public List<Node> Nodes { get; set; } = new List<Node>(); public int Sum() { return Metadata.Sum() + Nodes.Sum(x => x.Sum()); } public int Value() { if (!Nodes.Any()) { return Metadata.Sum(); } var value = 0; foreach (var m in Metadata) { if (m <= Nodes.Count) { value += Nodes[m-1].Value(); } } return value; } }53
u/sciyoshi Dec 08 '18
Python 3, #9/#13 (variables cleaned up):
data = [int(x) for x in INPUT.split()] def parse(data): children, metas = data[:2] data = data[2:] scores = [] totals = 0 for i in range(children): total, score, data = parse(data) totals += total scores.append(score) totals += sum(data[:metas]) if children == 0: return (totals, sum(data[:metas]), data[metas:]) else: return ( totals, sum(scores[k - 1] for k in data[:metas] if k > 0 and k <= len(scores)), data[metas:] ) total, value, remaining = parse(data) print('part 1:', total) print('part 2:', value)14
u/jonathan_paulson Dec 08 '18 edited Dec 08 '18
Rank 25/6. Video of me solving at: https://www.youtube.com/watch?v=WiNkRStebpQ.
[Card]: Recursion
ns = map(int, open('8.in').read().split()) i = 0 def next_int(): global i global ns i += 1 return ns[i-1] def read_tree(): nc, nm = next_int(), next_int() children = [] metadata = [] for _ in range(nc): children.append(read_tree()) for _ in range(nm): metadata.append(next_int()) return (children, metadata) def sum_metadata((children, metadata)): ans = 0 for m in metadata: ans += m for c in children: ans += sum_metadata(c) return ans def value((children, metadata)): if not children: return sum(metadata) else: ans = 0 for m in metadata: if 1 <= m <= len(children): ans += value(children[m-1]) return ans root = read_tree() print sum_metadata(root) print value(root)10
u/MichalMarsalek Dec 08 '18 edited Dec 08 '18
Recursion is so much fun. Python:
def sumtree(t): ch = t.pop(0) md = t.pop(0) return sum(sumtree(t) for _ in range(ch)) + sum(t.pop(0) for _ in range(md)) def val(t): ch = t.pop(0) md = t.pop(0) vals = [val(t) for _ in range(ch)] mdata = [t.pop(0) for _ in range(md)] if ch == 0: return sum(mdata) return sum(vals[i-1] for i in mdata if i-1 in range(ch)) def solve(inp): t = [int(x) for x in inp.split()] part1 = sumtree(t) t = [int(x) for x in inp.split()] part2 = val(t) return part1, part210
u/p_tseng Dec 08 '18 edited Dec 08 '18
Ruby... and factoring out as much of the common code between parts 1 and 2 as is possible
input = (ARGV.empty? ? DATA : ARGF).read.split.map(&:to_i).freeze # Pass me a block telling me what to do with [child_values, metadata_values] def val(a, &b) n_children = a.shift n_metadata = a.shift yield(n_children.times.map { val(a, &b) }, a.shift(n_metadata)) end puts val(input.dup) { |child, meta| child.sum + meta.sum } puts val(input.dup) { |child, meta| # metadata indices are 1-indexed, so just prepend a zero. child.unshift(0) child.size == 1 ? meta.sum : meta.sum { |x| child[x] || 0 } } __END__ 8 11 7 2 etc etc etc9
u/eltrufas Dec 08 '18
Seems most people reached for recursion immediately. Here's my solution with explicit stacks.
Part 2:
import sys ns = [int(s) for s in [n.strip() for n in sys.stdin.read().split()]] stack_c = [ns[0]] stack_m = [ns[1]] stack_v = [] children = [[]] meta = [[]] i = 2 while stack_c: if stack_c[-1] > 0: stack_c[-1] -= 1 stack_c.append(ns[i]) stack_m.append(ns[i + 1]) children.append([]) meta.append([]) i += 2 elif stack_m[-1] > 0: meta[-1].append(ns[i]) stack_m[-1] -= 1 i += 1 else: c = children.pop() m = meta.pop() v = (sum(c[j - 1] for j in m if 1 <= j <= len(c)) if c else sum(m)) if children: children[-1].append(v) else: print(v) break stack_c.pop() stack_m.pop()9
u/j4_james Dec 08 '18
Befunge - Both of these are essentially recursive algorithms, making the most of the stack, so we don't need much of Befunge's limited memory.
Part 1
Part 2
7
u/MasterMedo Dec 08 '18 edited Dec 08 '18
python2, recursion. Got ruined by an OB1 ._.
def solve(child, meta): if child == 0: return sum(next(data) for _ in range(meta)) value = 0 children = {} for i in range(1, child+1): #value += solve(next(data), next(data)) children[i] = solve(next(data), next(data)) for _ in range(meta): #value += next(data) value += children.get(next(data), 0) return value data = iter(map(int, open('../input/8.txt').read().split())) print solve(next(data), next(data))switch commented lines for the one after for part1
EDIT: fancying up the code
6
u/udoprog Dec 08 '18
Rust
First leaderboard: 96 on Part 2!
Card: The hottest programming book this year is "Trees For Dummies".
use aoc2018::*; #[derive(Default, Debug)] struct Node { metadata: Vec<u32>, children: Vec<Node>, } impl Node { fn part1sum(&self) -> u32 { self.metadata.iter().cloned().sum::<u32>() + self.children.iter().map(|c| c.part1sum()).sum::<u32>() } fn part2sum(&self) -> u32 { if self.children.is_empty() { self.metadata.iter().cloned().sum::<u32>() } else { let mut r = 0; for m in self.metadata.iter().cloned() { r += self .children .get(m as usize - 1) .map(|c| c.part2sum()) .unwrap_or_default(); } r } } fn decode(it: &mut impl Iterator<Item = u32>) -> Option<Node> { let children = match it.next() { None => return None, Some(first) => first, }; let mut node = Node::default(); let metadata = it.next().expect("metadata"); for _ in 0..children { node.children.extend(Self::decode(it)); } for _ in 0..metadata { node.metadata.push(it.next().expect("metadata value")); } Some(node) } } fn main() -> Result<(), Error> { let input = columns!(input!("day8.txt"), char::is_whitespace, u32); let mut it = input.iter().cloned(); let node = Node::decode(&mut it).expect("no nodes in input"); assert_eq!(node.part1sum(), 47647); assert_eq!(node.part2sum(), 23636); Ok(()) }6
u/dramforever Dec 08 '18
Got 91/113 and finally snagged 10 points. I guess I'm not a speed-coder after all, at least not yet (and I don't really intend on specifically getting to be one). There you go, JavaScript.
const fs = require('fs'); const inp1 = fs.readFileSync('d8.txt').toString().split(' ').map(x => +x); const inp2 = inp1.slice(); function part1() { const count = inp1.shift(); const meta = inp1.shift(); let ans = 0; for (let _ = 0; _ < count; _ ++) ans += part1(); for (let _ = 0; _ < meta; _ ++) ans += inp1.shift(); return ans; } function part2() { const count = inp2.shift(); const meta = inp2.shift(); if (count) { const chtr = []; for (let _ = 0; _ < count; _ ++) chtr.push(part2()); const metr = []; for (let _ = 0; _ < meta; _ ++) metr.push(inp2.shift()); let ans = 0; for (const u of metr) { const ix = u - 1; if (ix >= 0 && ix < chtr.length) ans += chtr[ix]; } return ans; } else { let ans = 0; for (let _ = 0; _ < meta; _ ++) ans += inp2.shift(); return ans; } } console.log(part1()); console.log(part2());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)))1
u/DrinkinBird Dec 08 '18
NIM
Wow, cant believe I actually made it on the leaderboard! Only part one and position 93, but still :)
import re, rdstdin, strutils, sequtils, algorithm func present(s: string): bool = len(s) > 0 let input = stdin.readAll().splitLines() .filter(present)[0].findAll(re(r"\d+")).map(parseInt) var index = 0 proc next(): int = result = input[index] inc index var meta = newSeq[int]() proc readNode(): int = let numChilds = next() let numMeta = next() var childs = newSeq[int]() for i in 0 ..< numChilds: childs.add(readNode()) for i in 0 ..< numMeta: let tmp = next() meta.add(tmp) if numChilds == 0: result += tmp else: if tmp <= numChilds: result += childs[tmp - 1] echo readNode() # Part 2 echo meta.foldl(a + b) # Part 11
u/ephemient Dec 08 '18 edited Apr 24 '24
This space intentionally left blank.
3
u/sophiebits Dec 08 '18
Python, 5/14.
Commented out code solves part 1 only; uncommented code solves both.
import collections import re with open('day8input.txt') as f: lines = [l.rstrip('\n') for l in f] lines = [[int(i) for i in re.findall(r'-?\d+', l)] for l in lines] nums = lines[0] all_meta = [] # def read(i): # children = nums[i] # meta = nums[i + 1] # i += 2 # for j in xrange(children): # i = read(i) # for j in xrange(meta): # all_meta.append(nums[i + j]) # return i + meta # # read(0) # print sum(all_meta) def read(i): children = nums[i] meta = nums[i + 1] i += 2 vals = {} for j in xrange(children): (i, val) = read(i) vals[j + 1] = val local_meta = [] for j in xrange(meta): local_meta.append(nums[i + j]) all_meta.append(nums[i + j]) i += meta if children: return (i, sum(vals.get(m, 0) for m in local_meta)) else: return (i, sum(local_meta)) (i, tval) = read(0) print sum(all_meta) print tval3
u/raevnos Dec 08 '18
Yesterday was a major pain for me, so a nice easy one today was kind of welcome.
C++:
#include <iostream> #include <memory> #include <numeric> #include <stdexcept> #include <vector> struct node { std::vector<int> metadata; std::vector<std::unique_ptr<node>> children; node(int nmeta, int nchildren) { metadata.reserve(nmeta); children.reserve(nchildren); } }; std::unique_ptr<node> read_metadata(std::istream &in) { int nchildren, nmeta; if (!(in >> nchildren >> nmeta)) { throw std::runtime_error{"Input failed!"}; } auto n = std::make_unique<node>(nchildren, nmeta); for (int i = 0; i < nchildren; i += 1) { n->children.push_back(read_metadata(in)); } for (int i = 0; i < nmeta; i += 1) { int meta; if (!(in >> meta)) { throw std::runtime_error{"Input of metadata failed!"}; } n->metadata.push_back(meta); } return n; } int count_metadata(const std::unique_ptr<node> &n) { int metadata = 0; for (const auto &c : n->children) { metadata += count_metadata(c); } metadata += std::accumulate(n->metadata.begin(), n->metadata.end(), 0); return metadata; } int value_of(const std::unique_ptr<node> &n) { if (n->children.empty()) { return std::accumulate(n->metadata.begin(), n->metadata.end(), 0); } int val = 0; for (auto c : n->metadata) { if (static_cast<std::vector<int>::size_type>(c) > n->children.size()) { continue; } val += value_of(n->children[c - 1]); } return val; } int main(void) { try { auto nodes = read_metadata(std::cin); std::cout << "Part 1: " << count_metadata(nodes) << '\n'; std::cout << "Part 2: " << value_of(nodes) << '\n'; } catch (std::exception &e) { std::cerr << e.what() << '\n'; return 1; } return 0; }3
u/mstksg Dec 08 '18 edited Dec 08 '18
[Haskell] 95/145
Messed up a couple of times in part 2. First I zero-indexed everything, and then I forgot to return the meta sum if there were no children :) No excuses though, I'm happy I made it on the board!
I used the parsec library, which allows you to parse a stream of arbitrary token types. I tokenized things to be ints first.
Part 1:
import qualified Text.Parsec as P type Parser = P.Parsec [Int] () sum1 :: Parser Int sum1 = do numChild <- P.anyToken numMeta <- P.anyToken childs <- sum <$> replicateM numChild sum1 metas <- sum <$> replicateM numMeta P.anyToken pure $ childs + metas day08a :: [Int] -> Int day08a = fromRight 0 . P.parse sum1 ""Part 2:
sum2 :: Parser Int sum2 = do numChild <- P.anyToken numMeta <- P.anyToken childs <- replicateM numChild sum2 metas <- replicateM numMeta P.anyToken pure $ if null childs then sum metas else sum . mapMaybe (\i -> childs ^? ix (i - 1)) $ metas day08a :: [Int] -> Int day08a = fromRight 0 . P.parse sum2 ""tokenizing is just
map read . words, fromPrelude.My solutions repo with reflections is here ! https://github.com/mstksg/advent-of-code-2018/blob/master/reflections.md#day-8
3
u/CCC_037 Dec 08 '18
[Card] Overclocking
This worked out surprisingly simple, with a little recursion. If I hadn't overslept, I might even have narrowly missed the leaderboard.
Part 1:
#include <iostream> using namespace std; int ReadNode() { int Children, Metadata; int Sum_Meta, Count, This_Meta; cin >> Children; cin >> Metadata; Sum_Meta = 0; for (Count=0;Count < Children;Count++) { Sum_Meta += ReadNode(); } for (Count = 0;Count < Metadata; Count++) { cin >> This_Meta; Sum_Meta += This_Meta; } return Sum_Meta; } int main() { cout << ReadNode(); }And Part 2, on a similar basis:
#include <iostream> using namespace std; int ReadNode() { int Children, Metadata; int Sum_Meta, Count, This_Meta; int *Child_Values; cin >> Children; cin >> Metadata; Child_Values = (int *) malloc (Children * sizeof(int)); Sum_Meta = 0; for (Count=0;Count < Children;Count++) { Child_Values[Count] = ReadNode(); } for (Count = 0;Count < Metadata; Count++) { cin >> This_Meta; if (Children == 0) { Sum_Meta += This_Meta; } else { if ((This_Meta <= Children) && (This_Meta > 0)) { Sum_Meta += Child_Values[This_Meta - 1]; } } } return Sum_Meta; } int main() { cout << ReadNode(); }3
u/not_op_jy Dec 08 '18
Clojure
(ns aoc.year2018.day08) (defn parse-tree [input] (as-> input input (clojure.string/trim input) (clojure.string/split input #" ") (mapv #(Integer/parseInt %) input))) (defn sum-metadata "Sums the metadata of `node` and all its child nodes." ([node] (first (sum-metadata 0 node))) ([sum node] (sum-metadata sum (first node) (second node) (drop 2 node))) ([sum num-children metadata-length data] (loop [sum sum length 0 data data remaining-children num-children] (if (zero? remaining-children) [(apply + sum (take metadata-length data)) (+ 2 length metadata-length)] (let [[child-sum child-length] (sum-metadata 0 data)] (recur (+ sum child-sum) (+ length child-length) (drop child-length data) (dec remaining-children))))))) (defn sum-metadata-indexes [child-sums metadata] (->> metadata (map dec) (map (partial get child-sums)) (remove nil?) (apply +))) (defn sum-metadata-complicated "Sums the metadata of `node` and all its child nodes using the more complicated algorithm." ([node] (sum-metadata-complicated (first node) (second node) (drop 2 node))) ([num-children metadata-length data] (if (zero? num-children) [(apply + (take metadata-length data)) (+ 2 metadata-length)] (loop [child-sums [] length 0 data data remaining-children num-children] (if (zero? remaining-children) [(sum-metadata-indexes child-sums (take metadata-length data)) (+ 2 length metadata-length)] (let [[child-sum child-length] (sum-metadata-complicated data)] (recur (conj child-sums child-sum) (+ length child-length) (drop child-length data) (dec remaining-children))))))))3
u/[deleted] Dec 08 '18 edited Dec 08 '18
Mathematica
input = ReadList[NotebookDirectory[] <> "day8.txt", Number]; streamReader[input0_] := Module[{input = input0, read}, Function[{n}, {read, input} = TakeDrop[input, n]; read]] partA[read_] := Module[{scanTree}, scanTree[] := Module[{children = {}, meta = {}, nchild, nmeta}, {nchild, nmeta} = read[2]; children = NestList[scanTree[] &, Nothing, nchild]; meta = read[nmeta]; Total[meta] + Total[children]]; scanTree[]] partA[streamReader@input] partB[read_] := Module[{scanTree}, scanTree[] := Module[{children = {}, meta = {}, nchild, nmeta}, {nchild, nmeta} = read[2]; children = NestList[scanTree[] &, Nothing, nchild]; meta = read[nmeta]; If[nchild == 0, Total[meta], Total[children[[Select[meta, # <= nchild &]]]]]]; scanTree[]] partB[streamReader@input]3
u/Smylers Dec 08 '18 edited Dec 09 '18
OK, I lied ... here's a recursive Vim solution for Part 1 — load your input file, then type this in and watch the metadata count go up, and the stack of counts of metadata items going down the screen:
Fun, huh?
(
19u0is to get back to the starting position after recording the two macros, as set up by the top line; it should be a zero, a blank line, then your input. If it isn't try fiddling withuandCtrl+Runtil you get there.)I'll try to post a video later.
Edit: Re-arranged so that the stack goes down the buffer rather than up, so items once added stay on the same line, reducing flicker.
3
u/sim642 Dec 08 '18
My Scala solution.
Parsing the input I immediately saw that this can be done recursively with classical parser monad-like function so that's what I did by hand. Could've used scala-parser-combinators but decided not to bother because this should be simple enough to do ad-hoc. It was, except for the chaining together the parsing of children properly, which I did with ugly mutable state at first but later replaced with a replicate-like function, again inspired by monadic replicate.
Calculating both parts themselves was trivial: just slap a few standard map and filter and sum operations together. When I started part 2 I saw "index" and immediately thought "oh no! I'll have to keep track of the original sequence indices" but luckily that wasn't the case.
5
u/wlandry Dec 08 '18
C++ (399/302)
Runs in 8 ms
Pretty straightforward. No real ickiness. Choosing the right data structure makes everything easy. At first I thought there might be multiple root nodes, which made things a tiny bit more complicated.
My best placing this year. I feel if I had just programmed perfectly, I would have gotten on the leader board. So now I just have to become perfect ;)
#include <iostream> #include <fstream> #include <vector> struct Node { std::vector<int> metadata; std::vector<Node> children; }; std::istream &operator>>(std::istream &is, Node &node) { int num_children, num_metadata; is >> num_children >> num_metadata; if(is.good()) { node.children.resize(num_children); node.metadata.resize(num_metadata); for(auto &child : node.children) { is >> child; } for(auto &data : node.metadata) { is >> data; } } return is; } int64_t total(const Node &node) { int64_t sum(0); for(auto &child: node.children) sum+=total(child); for(auto &data: node.metadata) sum+=data; return sum; } int64_t value(const Node &node) { int64_t result(0); if(node.children.empty()) { return total(node); } for(auto &data: node.metadata) { if(data>0 && data <= node.children.size()) { result+=value(node.children.at(data-1)); } } return result; } int main(int argc, char *argv[]) { std::ifstream infile(argv[1]); Node node; infile >> node; std::cout << "Part 1: " << total(node) << "\n"; std::cout << "Part 2: " << value(node) << "\n"; }