advent-of-code

advent of code (partial solutions)
Log | Files | Refs | README

commit 4d9ab89736f7ad36a1441a9948bd96fa78ccf40d
parent 04ea046478277fe2a0c268babb39dd12a11cb7cc
Author: alex wennerberg <alex@alexwennerberg.com>
Date:   Thu,  9 Dec 2021 19:17:47 -0800

day 9

Diffstat:
A2021/aoc09.py | 82+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
1 file changed, 82 insertions(+), 0 deletions(-)

diff --git a/2021/aoc09.py b/2021/aoc09.py @@ -0,0 +1,82 @@ +import sys +import operator +from collections import Counter +from functools import reduce + +lines = sys.stdin.read()[:-1].split("\n") +arr = [[b for b in a] for a in lines] + +class Point: + def __init__(self): + self.val = 10 + self.x = None + self.y = None + + def __eq__(self, other): + return self.x == other.x and self.y == other.y + + def __hash__(self): + return hash((self.x, self.y)) + + def __gt__(self, other): + return self.val > other.val + + def __lt__(self, other): + return self.val < other.val + + def left(self): + return points.get((self.x-1, self.y)) or Point() + + def right(self): + return points.get((self.x+1, self.y)) or Point() + + def down(self): + return points.get((self.x, self.y+1)) or Point() + + def up(self): + return points.get((self.x, self.y-1)) or Point() + + def __repr__(self): + return "{} {} {}".format(self.x, self.y, self.val) + + def get_basin(self, last=None): + if last is None: + last = Point() + b = set() + for s in self.right(), self.left(), self.up(), self.down(): + if s != last and s != Point() and s.val < 9 and s.val >= self.val and s not in b: + b |= s.get_basin(self) + b.add(self) + print(self) + return b + +points = {} + +for n, row in enumerate(arr): + for m, col in enumerate(row): + point = Point() + point.x = m + point.y = n + point.val = int(col) + points[(m,n)] = point + + +total = 0 + +for k, point in points.items(): + if point.left() > point and point.right() > point and point.up() > point and point.down() > point: + point.basin = True + total += 1 + point.val + else: + point.basin = False + +print(total) + +basins = [] + +for k, point in points.items(): + if point.basin: + b = point.get_basin() + basins.append(b) + +print(reduce(operator.mul, [len(a) for a in sorted(basins, key=len, reverse=True)[:3]]), 1)