Add solution for day 10

This commit is contained in:
William Brawner 2024-12-11 22:06:06 -07:00
parent 73471a8a69
commit c87daab18b
Signed by: wbrawner
GPG key ID: 8FF12381C6C90D35

103
src/day10.py Normal file
View file

@ -0,0 +1,103 @@
#!/usr/bin/env python3
from util import print_color, read_input, Color
cardinals = [
# up
lambda row, col: (row - 1, col),
# down
lambda row, col: (row + 1, col),
# left
lambda row, col: (row, col - 1),
# right
lambda row, col: (row, col + 1),
]
def find_next(grid, cur_row, cur_col):
current_value = grid[cur_row][cur_col]
if not current_value.isdigit():
return []
current_value = int(current_value)
if current_value == 9:
return [(cur_row, cur_col)]
nines = []
for cardinal in cardinals:
(new_row, new_col) = cardinal(cur_row, cur_col)
if new_row < 0 or new_col < 0 or new_row >= len(grid) or new_col >= len(grid[0]):
continue
next_value = grid[new_row][new_col]
if not next_value.isdigit():
continue
next_value = int(next_value)
if next_value == current_value + 1:
nines.extend(find_next(grid, new_row, new_col))
return nines
def part1(input_lines):
zeroes = []
for row, line in enumerate(input_lines):
for col, char in enumerate(line):
if input_lines[row][col] == '0':
zeroes.append((row, col))
complete_trails = set()
for zero in zeroes:
for complete_trail in find_next(input_lines, zero[0], zero[1]):
complete_trails.add((zero, complete_trail))
return len(complete_trails)
def part2(input_lines):
zeroes = []
for row, line in enumerate(input_lines):
for col, char in enumerate(line):
if input_lines[row][col] == '0':
zeroes.append((row, col))
complete_trails = []
for zero in zeroes:
for complete_trail in find_next(input_lines, zero[0], zero[1]):
complete_trails.append((zero, complete_trail))
return len(complete_trails)
test_input = read_input("_test")
test_input_result = part1(test_input)
print_color(test_input_result, Color.GREY)
assert 1 == test_input_result
test_input = read_input("_test_2")
test_input_result = part1(test_input)
print_color(test_input_result, Color.GREY)
assert 2 == test_input_result
test_input = read_input("_test_3")
test_input_result = part1(test_input)
print_color(test_input_result, Color.GREY)
assert 4 == test_input_result
test_input = read_input("_test_4")
test_input_result = part1(test_input)
print_color(test_input_result, Color.GREY)
assert 3 == test_input_result
test_input = read_input("_test_5")
test_input_result = part1(test_input)
print_color(test_input_result, Color.GREY)
assert 36 == test_input_result
real_input = read_input()
print(part1(real_input))
test_input = read_input("_test_6")
test_input_result = part2(test_input)
print_color(test_input_result, Color.GREY)
assert 3 == test_input_result
test_input = read_input("_test_5")
test_input_result = part2(test_input)
assert 81 == test_input_result
print(part2(real_input))