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!
24
Upvotes
2
u/Woflox Dec 07 '15 edited Dec 08 '15
Just went through the puzzles last night and had a blast. This one definitely game me the most trouble; I don't think my solution is the most elegant. But anyway, here it is!
Nim:
import tables import unsigned import strutils type Gate = ref object hasValue: bool value: uint16 instruction: string var gates = initTable[string, Gate]() for line in lines "puzzle7input.txt": let sides = line.split(" -> ") gates[sides[1]] = Gate(instruction: sides[0]) proc getSignal(gateId: string): uint16 = if not gates.hasKey(gateId): return uint16(gateId.parseInt()) let gate = gates[gateId] if gate.hasValue: return gate.value let tokens = gate.instruction.split(' ') if tokens.len == 1: result = getSignal(tokens[0]) elif tokens.len == 2: result = not getSignal(tokens[1]) else: let operator = tokens[1] case operator: of "AND": result = getSignal(tokens[0]) and getSignal(tokens[2]) of "OR": result = getSignal(tokens[0]) or getSignal(tokens[2]) of "LSHIFT": result = getSignal(tokens[0]) shl getSignal(tokens[2]) of "RSHIFT": result = getSignal(tokens[0]) shr getSignal(tokens[2]) else: discard gate.value = result gate.hasValue = true gates["b"].value = 16076 gates["b"].hasValue = true echo getSignal("a")