AdventOfCode/2017/08/solution.py

137 lines
3.6 KiB
Python
Raw Permalink Normal View History

2024-11-22 15:12:35 +01:00
#!/bin/python3
import sys,re
from pprint import pprint
input_f = 'input'
part = 2
#########################################
# #
# Part 1 #
# #
#########################################
if part == 1:
grid = []
values = {}
with open(input_f) as file:
for line in file:
grid.append(line.rstrip())
#pprint(grid)
pattern = r"(\w+)\s(inc|dec)\s(-?\d+)\sif\s(\w+)\s([<>=!]+)\s(-?\d+)"
# Process each instruction
for instruction in grid:
match = re.match(pattern, instruction)
if match:
input_var = match.group(1)
change = match.group(2)
value = int(match.group(3))
con1 = match.group(4)
con2 = match.group(5)
con3 = int(match.group(6))
#print(f"input = {input_var}, change = {change}, value = {value}, con1 = {con1}, con2 = {con2}, con3 = {con3}")
else:
print(instruction)
print('NO MATCH')
exit()
#print(f"input = {input_var}, change = {change}, value = {value}, con1 = {con1}, con2 = {con2}, con3 = {con3}")
if input_var not in values:
values[input_var] = 0
if con1 not in values:
values[con1] = 0
condition = f"{values[con1]} {con2} {con3}"
#print('calculation =======',condition)
if eval(condition):
if change == 'inc':
values[input_var] += value
if change == 'dec':
values[input_var] -= value
#pprint(values)
max_v = 0
for key, i in values.items():
if max_v < i:
max_v = i
print(max_v)
#########################################
# #
# Part 2 #
# #
#########################################
def find_max(x):
#print(x)
max_v = 0
for key, i in values.items():
if max_v < i:
max_v = i
return max_v
if part == 2:
grid = []
values = {}
total_max = 0
with open(input_f) as file:
for line in file:
grid.append(line.rstrip())
#pprint(grid)
pattern = r"(\w+)\s(inc|dec)\s(-?\d+)\sif\s(\w+)\s([<>=!]+)\s(-?\d+)"
# Process each instruction
for instruction in grid:
match = re.match(pattern, instruction)
if match:
input_var = match.group(1)
change = match.group(2)
value = int(match.group(3))
con1 = match.group(4)
con2 = match.group(5)
con3 = int(match.group(6))
#print(f"input = {input_var}, change = {change}, value = {value}, con1 = {con1}, con2 = {con2}, con3 = {con3}")
else:
print(instruction)
print('NO MATCH')
exit()
#print(f"input = {input_var}, change = {change}, value = {value}, con1 = {con1}, con2 = {con2}, con3 = {con3}")
if input_var not in values:
values[input_var] = 0
if con1 not in values:
values[con1] = 0
condition = f"{values[con1]} {con2} {con3}"
#print('calculation =======',condition)
if eval(condition):
if change == 'inc':
values[input_var] += value
if change == 'dec':
values[input_var] -= value
temp_max = find_max(values)
if total_max < temp_max:
total_max = temp_max
#print('New Max Found',total_max)
print(total_max)
#pprint(values)