Files
AdventOfCode2024/24/24-01.py
2024-12-25 10:43:39 +01:00

70 lines
1.9 KiB
Python

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from time import time
from copy import deepcopy
import re
start_time = time()
file = "./input.txt"
# file = "./ex-small.txt"
# file = "./ex-big.txt"
def read_and_parse(input_file: str) -> tuple[dict[str:int], list[tuple[str, str, str, str]]]:
result_dict = {}
with open(input_file, 'r') as d:
datei = d.read()
pat_dict = r'(.+)\: +(\d)'
pat_list = r'(.+) +(.+) +(.+) +\-\> +(.+)'
match_d = re.findall(pat_dict, datei)
# print(match_d)
for d in match_d:
result_dict[d[0]] = int(d[1])
match_l = re.findall(pat_list, datei)
# print(match_l)
return result_dict, match_l
if __name__ == "__main__":
in_dict, in_list = read_and_parse(file)
var_found = True
while var_found:
var_found = False
temp = []
for e in in_list:
if e[0] in in_dict and e[2] in in_dict:
var_found = True
if e[1] == "AND":
if in_dict[e[0]] == 1 and in_dict[e[2]] == 1:
in_dict[e[3]] = 1
else:
in_dict[e[3]] = 0
elif e[1] == "OR":
if in_dict[e[0]] == 1 or in_dict[e[2]] == 1:
in_dict[e[3]] = 1
else:
in_dict[e[3]] = 0
elif e[1] == "XOR":
if in_dict[e[0]] != in_dict[e[2]]:
in_dict[e[3]] = 1
else:
in_dict[e[3]] = 0
else:
temp.append(e)
in_list = deepcopy(temp)
print()
print(in_dict)
print(in_list)
z_keys = sorted([key for key in in_dict if key.startswith("z")], reverse=True)
print(z_keys)
sol = ""
for z in z_keys:
sol += str(in_dict[z])
print(sol)
print(f'Solution Part1: {int(sol, 2)}')
print(f'Runtime: {time() - start_time:.2f} s')