Created
December 14, 2015 14:35
-
-
Save TimCastelijns/4b8698d2a0da6847b278 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
processed_lines = [] | |
known_keys = [] | |
mapping = {} | |
def is_entire_lhand_known(line): | |
ops = ('OR', 'AND', 'NOT', 'LSHIFT', 'RSHIFT') | |
keys = [] | |
for part in [x.strip() for x in line[:line.index('->')].split()]: | |
if part not in ops and not part.isdigit(): | |
keys.append(part) | |
return all([k in known_keys for k in keys]) | |
def is_number_signal_provider(line): | |
return line.split()[0].isdigit() and len(line.split()) == 3 and line.split()[1] == '->' | |
def process_line(line): | |
instructions = line.strip().split() | |
target = instructions[-1] | |
if instructions[1] == 'RSHIFT': | |
first = instructions[0] | |
second = instructions[2] | |
if first.isdigit() and not second.isdigit(): | |
value = first / 2**int(second) | |
elif not first.isdigit() and second.isdigit(): | |
value = mapping[first] / 2**int(second) | |
else: | |
value = mapping[first] / 2**int(second) | |
mapping[target] = value | |
elif instructions[1] == 'LSHIFT': | |
first = instructions[0] | |
second = instructions[2] | |
value = mapping[first] * 2**int(second) | |
mapping[target] = value | |
elif instructions[1] == 'AND': | |
first = instructions[0] | |
second = instructions[2] | |
if first.isdigit() and not second.isdigit(): | |
value = int(first) & mapping[second] | |
elif not first.isdigit() and second.isdigit(): | |
value = mapping[first] & second | |
else: | |
value = mapping[first] & mapping[second] | |
mapping[target] = value | |
elif instructions[1] == 'OR': | |
first = instructions[0] | |
second = instructions[2] | |
value = mapping[first] | mapping[second] | |
mapping[target] = value | |
elif instructions[0] == 'NOT': | |
mapping[target] = 65535 - mapping[instructions[1]] | |
else: # provide signal to target wire. | |
value = mapping[instructions[0]] | |
mapping[target] = value | |
known_keys.append(target) | |
known_keys.append(target) | |
with open('day7.txt', 'r') as f: | |
s = f.readlines() | |
while len(s) > len(processed_lines): | |
for line in [l.strip() for l in s]: | |
if line in processed_lines: | |
continue | |
if is_number_signal_provider(line): | |
instructions = line.strip().split() | |
target = instructions[-1] | |
value = int(instructions[0]) | |
mapping[target] = value | |
known_keys.append(target) | |
processed_lines.append(line) | |
continue | |
if is_entire_lhand_known(line): | |
process_line(line) | |
processed_lines.append(line) | |
print mapping['a'] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment