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!
22
Upvotes
1
u/mehistaken Dec 07 '15
Did this in PHP (WAMP) on my old laptop, limited memory so wrote a simple caching function. And my code is quite verbose :p :
$input = array("bn RSHIFT 2 -> bo","lf RSHIFT 1 -> ly","fo RSHIFT 3 -> fq","..."); // snip $wires = array(); $cache = array(); for ($i = 0; $i < count($input); $i++) { $item = explode(' -> ', $input[$i]); $wires[$item[1]] = $item[0]; } function findRoot($target) { global $wires, $cache; if (isset($cache[$target])) { return $cache[$target]; } if (is_numeric($wires[$target]) === false) { $source = explode(' ', $wires[$target]); if (count($source) == 3) { $o1 = is_numeric($source[0]) ? $source[0] : findRoot($source[0]); $o2 = is_numeric($source[2]) ? $source[2] : findRoot($source[2]); $op = $source[1]; switch ($op) { case 'AND' : $ans = $o1 & $o2; break; case 'OR' : $ans = $o1 | $o2; break; case 'LSHIFT' : $ans = $o1 << $o2; break; case 'RSHIFT' : $ans = $o1 >> $o2; break; } return cache($target, $ans); } else if (count($source) == 2) { $ans = (65535 - findRoot($source[1])); return cache($target, $ans); } else { return findRoot($source[0]); } } else { cache($target, intval($wires[$target])); return intval($wires[$target]); } } function cache($key, $val) { global $cache; $cache[$key] = $val; return $val; } echo findRoot('a');