Created
December 5, 2019 16:46
-
-
Save zer0tonin/cfe5e7b528d912bc9f6e3a09bf0ec050 to your computer and use it in GitHub Desktop.
Advent of Code day 5
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
def param_accessor(instruction, position): | |
try: | |
if instruction[-2 - position] == "1": | |
return lambda pointer, opcodes: opcodes[pointer+position] | |
except IndexError: | |
pass | |
return lambda pointer, opcodes: opcodes[opcodes[pointer+position]] | |
def op_sum(pointer, opcodes, first_param, second_param): | |
opcodes[opcodes[pointer+3]] = first_param(pointer, opcodes) + second_param(pointer, opcodes) | |
return pointer + 4 | |
def op_mul(pointer, opcodes, first_param, second_param): | |
opcodes[opcodes[pointer+3]] = first_param(pointer, opcodes) * second_param(pointer, opcodes) | |
return pointer + 4 | |
def op_input(pointer, opcodes, *_): | |
print("input") | |
opcodes[opcodes[pointer+1]] = int(input()) | |
return pointer + 2 | |
def op_print(pointer, opcodes, first_param, _): | |
print("result: {}".format(first_param(pointer, opcodes))) | |
return pointer + 2 | |
def op_jump_if_true(pointer, opcodes, first_param, second_param): | |
if first_param(pointer, opcodes) != 0: | |
return second_param(pointer, opcodes) | |
return pointer + 3 | |
def op_jump_if_false(pointer, opcodes, first_param, second_param): | |
if first_param(pointer, opcodes) == 0: | |
return second_param(pointer, opcodes) | |
return pointer + 3 | |
def op_less_than(pointer, opcodes, first_param, second_param): | |
opcodes[opcodes[pointer+3]] = 1 if first_param(pointer, opcodes) < second_param(pointer, opcodes) else 0 | |
return pointer + 4 | |
def op_equal(pointer, opcodes, first_param, second_param): | |
opcodes[opcodes[pointer+3]] = 1 if first_param(pointer, opcodes) == second_param(pointer, opcodes) else 0 | |
return pointer + 4 | |
def end(*_): | |
return None | |
OPERATIONS = { | |
"1": op_sum, | |
"2": op_mul, | |
"3": op_input, | |
"4": op_print, | |
"5": op_jump_if_true, | |
"6": op_jump_if_false, | |
"7": op_less_than, | |
"8": op_equal, | |
"9": end, | |
} | |
def evaluate(opcodes): | |
pointer = 0 | |
while pointer is not None: | |
instruction = str(opcodes[pointer]) | |
print("instruction: {}".format(instruction)) | |
first_param = param_accessor(instruction, 1) | |
second_param = param_accessor(instruction, 2) | |
pointer = OPERATIONS[instruction[-1]](pointer, opcodes, first_param, second_param) | |
return opcodes | |
with open("input") as stream: | |
opcodes = stream.readlines()[0].strip().split(',') | |
opcodes = [int(opcode) for opcode in opcodes] | |
evaluate(opcodes) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment