66 lines
1.9 KiB
Python
66 lines
1.9 KiB
Python
import aoclib
|
|
|
|
DAY = 8
|
|
TEST_SOLUTION_PART1 = 5
|
|
TEST_SOLUTION_PART2 = 8
|
|
|
|
|
|
def optimizeInput(input_array):
|
|
return_array = []
|
|
for line in input_array:
|
|
command, param = line.split()
|
|
param = int(param)
|
|
return_array.append((command, param))
|
|
|
|
return return_array
|
|
|
|
|
|
def runCode(lines, infinite_returns_value=False, infinite_returns_set=False):
|
|
accumulator = 0
|
|
line_pointer = 0
|
|
lines_executed = set()
|
|
last_line = len(lines)
|
|
while line_pointer < last_line:
|
|
if line_pointer in lines_executed:
|
|
if infinite_returns_value:
|
|
return accumulator
|
|
elif infinite_returns_set:
|
|
return lines_executed
|
|
else:
|
|
return None
|
|
|
|
lines_executed.add(line_pointer)
|
|
command, param = lines[line_pointer]
|
|
if command == 'nop':
|
|
line_pointer += 1
|
|
elif command == 'acc':
|
|
accumulator = accumulator + param
|
|
line_pointer += 1
|
|
elif command == 'jmp':
|
|
line_pointer = line_pointer + param
|
|
|
|
return accumulator
|
|
|
|
|
|
def part1(test_mode=False):
|
|
my_input = aoclib.getInputAsArray(day=DAY, test=test_mode)
|
|
return runCode(optimizeInput(my_input), infinite_returns_value=True)
|
|
|
|
|
|
def part2(test_mode=False):
|
|
my_input = aoclib.getInputAsArray(day=DAY, test=test_mode)
|
|
opt_input = optimizeInput(my_input)
|
|
for exec_line in runCode(opt_input, infinite_returns_set=True):
|
|
if opt_input[exec_line][0] not in ['nop', 'jmp']:
|
|
continue
|
|
|
|
check_code = opt_input[:]
|
|
if opt_input[exec_line][0] == 'jmp':
|
|
check_code[exec_line] = ('nop', check_code[exec_line][1])
|
|
elif opt_input[exec_line][0] == 'nop':
|
|
check_code[exec_line] = ('jmp', check_code[exec_line][1])
|
|
|
|
check_answer = runCode(check_code)
|
|
if check_answer is not None:
|
|
return check_answer
|