advent_of_code/2021/9/9.py

88 lines
2.4 KiB
Python
Raw Normal View History

2021-12-09 13:22:21 +01:00
#!/usr/bin/env python
# 2021 - Advent Of Code - 9
2022-11-30 01:48:52 +01:00
# 2022: cheat for pylint to start fresh for 2022
# pylint: disable=unnecessary-list-index-lookup
2021-12-09 13:22:21 +01:00
def parse_file(file):
hmap = []
2022-04-05 13:27:24 +02:00
with open(file, encoding="utf-8") as f:
2021-12-09 13:22:21 +01:00
for line in f.readlines():
linemap = []
for n in line.strip():
linemap.append(int(n))
hmap.append(linemap)
return hmap
def print_hmap(hmap):
2021-12-13 05:38:24 +01:00
for y, _ in enumerate(hmap):
for x, _ in enumerate(hmap[y]):
2021-12-09 13:22:21 +01:00
print(hmap[y][x], end='')
print()
def find_lowpoints(hmap):
2022-04-05 14:02:10 +02:00
# pylint: disable=R0912
2021-12-09 13:22:21 +01:00
lpoints = []
# first line
x = 0
y = 0
if hmap[y][x] < hmap[y][x + 1] and hmap[y][x] < hmap[y + 1][x]:
lpoints.append([x, y])
for x in range(1, len(hmap[y]) - 1):
v = hmap[y][x]
if v < hmap[y][x - 1] and v < hmap[y][x + 1] and v < hmap[y + 1][x]:
lpoints.append([x, y])
x = len(hmap[y]) - 1
if hmap[y][x] < hmap[y][x - 1] and hmap[y][x] < hmap[y + 1][x]:
lpoints.append([x, y])
# middle lines
for y in range(1, len(hmap) - 1):
x = 0
if hmap[y][x] < hmap[y][x + 1] and hmap[y][x] < hmap[y - 1][x] and hmap[y][x] < hmap[y + 1][x]:
lpoints.append([x, y])
for x in range(1, len(hmap[y]) - 1):
v = hmap[y][x]
if v < hmap[y][x - 1] and v < hmap[y][x + 1] and v < hmap[y - 1][x] and v < hmap[y + 1][x]:
lpoints.append([x, y])
x = len(hmap[y]) - 1
if hmap[y][x] < hmap[y][x - 1] and hmap[y][x] < hmap[y - 1][x] and hmap[y][x] < hmap[y + 1][x]:
lpoints.append([x, y])
# last line
y = len(hmap) - 1
x = 0
if hmap[y][x] < hmap[y][x + 1] and hmap[y][x] < hmap[y - 1][x]:
lpoints.append([x, y])
for x in range(1, len(hmap[y]) - 1):
v = hmap[y][x]
if v < hmap[y][x - 1] and v < hmap[y][x + 1] and v < hmap[y - 1][x]:
lpoints.append([x, y])
x = len(hmap[y]) - 1
if hmap[y][x] < hmap[y][x - 1] and hmap[y][x] < hmap[y - 1][x]:
lpoints.append([x, y])
return lpoints
# heightmap = parse_file('input_example.txt')
heightmap = parse_file('input.txt')
# print_hmap(heightmap)
low_points = find_lowpoints(heightmap)
risk_levels = 0
for p in low_points:
print(f'low point at {p}, value {heightmap[p[1]][p[0]]}')
risk_levels += heightmap[p[1]][p[0]] + 1
print(f'The sum of risk levels is {risk_levels}')