Compare commits

...

2 commits

Author SHA1 Message Date
dece 24ee5520bf Day 10 2021-12-10 13:25:43 +01:00
dece a1a099c712 Day 9 2021-12-09 14:25:21 +01:00
2 changed files with 90 additions and 0 deletions

37
2021/day10.py Normal file
View file

@ -0,0 +1,37 @@
import sys
CHARMAP = {"]": "[", ")": "(", "}": "{", ">": "<"}
SCOREMAP = {")": 3, "]": 57, "}": 1197, ">": 25137}
SCOREMAP2 = {"(": 1, "[": 2, "{": 3, "<": 4}
def main():
lines = [line.rstrip() for line in sys.stdin]
error_score = 0
comp_scores = []
for line in lines:
corrupted = None
state = []
for char in line:
if char in CHARMAP:
if state and state[-1] == CHARMAP[char]:
state.pop()
else:
corrupted = char
break
else:
state.append(char)
if corrupted:
error_score += SCOREMAP[corrupted]
else:
cs = 0
for char in reversed(state):
cs = cs * 5 + SCOREMAP2[char]
comp_scores.append(cs)
print(error_score)
print(list(sorted(comp_scores))[len(comp_scores) // 2])
if __name__ == "__main__":
main()

53
2021/day9.py Normal file
View file

@ -0,0 +1,53 @@
import sys
def main():
lines = [line.rstrip() for line in sys.stdin]
nc = len(lines[0])
nr = len(lines)
m = [list(map(int, line)) for line in lines]
# Part 1
low_points = []
rlevels = 0
for x, row in enumerate(m):
for y, val in enumerate(row):
if (
(x == 0 or m[x - 1][y] > val)
and (x == nr - 1 or m[x + 1][y] > val)
and (y == 0 or m[x][y - 1] > val)
and (y == nc - 1 or m[x][y + 1] > val)
):
low_points.append((x, y)) # for part 2
rlevels += val + 1
print(rlevels)
# Part 2
basins = [expand_basin(m, (x, y), nc, nr) for x, y in low_points]
a, b, c = sorted(map(len, basins))[-3:]
print(a * b * c)
def expand_basin(m, start, nc, nr):
basin = []
sx, sy = start
explo = [(sx, sy)]
while explo:
pos = explo.pop(0)
x, y = pos
if m[x][y] == 9:
continue
basin.append(pos)
if x > 0 and (n := (x - 1, y)) not in basin and n not in explo:
explo.append(n)
if x < nr - 1 and (n := (x + 1, y)) not in basin and n not in explo:
explo.append(n)
if y > 0 and (n := (x, y - 1)) not in basin and n not in explo:
explo.append(n)
if y < nc - 1 and (n := (x, y + 1)) not in basin and n not in explo:
explo.append(n)
return basin
if __name__ == "__main__":
main()