Spaces:
Running
Running
def parse_schematics(file_path): | |
with open(file_path, 'r') as file: | |
lines = file.read().strip().split('\n') | |
locks = [] | |
keys = [] | |
current_schematic = [] | |
is_lock = True | |
for line in lines: | |
if line == '': | |
if current_schematic: | |
if is_lock: | |
locks.append(current_schematic) | |
else: | |
keys.append(current_schematic) | |
current_schematic = [] | |
is_lock = not is_lock | |
else: | |
current_schematic.append(line) | |
if current_schematic: | |
if is_lock: | |
locks.append(current_schematic) | |
else: | |
keys.append(current_schematic) | |
return locks, keys | |
def convert_to_heights(schematic, is_lock): | |
num_columns = len(schematic[0]) | |
num_rows = len(schematic) | |
heights = [0] * num_columns | |
if is_lock: | |
for col in range(num_columns): | |
for row in range(num_rows): | |
if schematic[row][col] == '#': | |
heights[col] += 1 | |
else: | |
for col in range(num_columns): | |
for row in range(num_rows - 1, -1, -1): | |
if schematic[row][col] == '#': | |
heights[col] += 1 | |
return heights | |
def count_fitting_pairs(locks, keys): | |
lock_heights = [convert_to_heights(lock, True) for lock in locks] | |
key_heights = [convert_to_heights(key, False) for key in keys] | |
num_rows = len(locks[0]) | |
fitting_pairs = 0 | |
for lock in lock_heights: | |
for key in key_heights: | |
if all(lock[col] + key[col] <= num_rows for col in range(len(lock))): | |
fitting_pairs += 1 | |
return fitting_pairs | |
file_path = "./input.txt" | |
locks, keys = parse_schematics(file_path) | |
result = count_fitting_pairs(locks, keys) | |
print(result) |