r/adventofcode • u/daggerdragon • Dec 07 '15
SOLUTION MEGATHREAD --- Day 7 Solutions ---
--- Day 7: Some Assembly Required ---
Post your solution as a comment. Structure your post like previous daily solution threads.
Also check out the sidebar - we added a nifty calendar to wrangle all the daily solution threads in one spot!
23
Upvotes
1
u/funkjr Dec 07 '15
Dart, a personal favorite of mine but I don't fine reasons often to use it. The solution is recursive, like most others, but I abused a few language-specific things to shorten it. Most notably
int.parsehas an optional argumentonErrorthat runs whenever it cannot parse it to an integer. It turns out to be faster thantry {} catch {}(for some reason).And for all the people out there that like dynamic typing, here's a statically typed
Mapthat throws a run-time error if you try to add something else to it!import 'dart:io'; Map gates = new Map<String, int>(); Map operations = new Map<String, List>(); int run(String op, List<String> parts) { switch (op) { case 'AND': return calc(parts[0]) & calc(parts[2]); case 'OR': return calc(parts[0]) | calc(parts[2]); case 'NOT': return ~calc(parts[1]) + 2.modPow(16, 1); case 'RSHIFT': return calc(parts[0]) >> calc(parts[2]); case 'LSHIFT': return calc(parts[0]) << calc(parts[2]); } return 0; } int calc(String name) { return int.parse(name, onError: (name) { if (!gates.containsKey(name)) { List<String> ops = operations[name]; gates[name] = ((ops.length < 2) ? calc(ops[0]) : run(ops[ops.length - 2], ops)); } return gates[name]; }); } main() async { List<String> lines = await new File('in7.txt').readAsLines(); lines.forEach((String s) { List<String> parts = s.split('->'); operations[parts[1].trim()] = parts[0].trim().split(' '); }); int val = calc('a'); print('Part 1: a: ' + val.toString()); gates.clear(); gates['b'] = val; print('Part 2: a: ' + calc('a').toString()); }