pre-optimizing the opcode makes p1 take twice the time, but p2 almost twice as fast
This commit is contained in:
parent
8277dfe0f9
commit
a8a0873eec
33
day08.py
33
day08.py
@ -5,6 +5,16 @@ 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
|
||||
@ -20,34 +30,35 @@ def runCode(lines, infinite_returns_value=False, infinite_returns_set=False):
|
||||
return None
|
||||
|
||||
lines_executed.add(line_pointer)
|
||||
command, param = lines[line_pointer].split()
|
||||
command, param = lines[line_pointer]
|
||||
if command == 'nop':
|
||||
line_pointer += 1
|
||||
elif command == 'acc':
|
||||
accumulator = accumulator + int(param)
|
||||
accumulator = accumulator + param
|
||||
line_pointer += 1
|
||||
elif command == 'jmp':
|
||||
line_pointer = line_pointer + int(param)
|
||||
line_pointer = line_pointer + param
|
||||
|
||||
return accumulator
|
||||
|
||||
|
||||
def part1(test_mode=False):
|
||||
my_input = aoclib.getInputAsArray(day=DAY, test=test_mode)
|
||||
return runCode(my_input, infinite_returns_value=True)
|
||||
return runCode(optimizeInput(my_input), infinite_returns_value=True)
|
||||
|
||||
|
||||
def part2(test_mode=False):
|
||||
my_input = aoclib.getInputAsArray(day=DAY, test=test_mode)
|
||||
for exec_line in runCode(my_input, infinite_returns_set=True):
|
||||
if not my_input[exec_line].startswith('nop') and not my_input[exec_line].startswith('jmp'):
|
||||
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 = my_input[:]
|
||||
if my_input[exec_line].startswith('jmp'):
|
||||
check_code[exec_line] = check_code[exec_line].replace('jmp', 'nop')
|
||||
elif my_input[exec_line].startswith('nop'):
|
||||
check_code[exec_line] = check_code[exec_line].replace('nop', 'jmp')
|
||||
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:
|
||||
|
||||
Loading…
Reference in New Issue
Block a user