My Advent of Code solutions in Python. kevinyap.ca/2019/12/going-fast-in-advent-of-code/
advent-of-code python
0
fork

Configure Feed

Select the types of activity you want to include in your feed.

Update solution for 2023/10

Use the polygon area formula that was pivotal to Day 18 to solve Day 10
Part 2. The points "enclosed" by the loop that can't escape is equal to
the internal area of the polygon after removing all points along the
perimeter, so that we don't double-count the loop itself.

+20 -2
+20 -2
2023/day10.py
··· 59 59 return None 60 60 61 61 node += direction 62 - loop.append(node) 63 62 64 63 if node == start: 65 64 return loop 65 + 66 + loop.append(node) 66 67 67 68 69 + def discrete_polygon_area(points): 70 + # Use shoelace formula to compute internal area. 71 + area = 0 72 + 73 + for a, b in zip(points, points[1:] + [points[0]]): 74 + area += (b.x + a.x) * (b.y - a.y) 75 + 76 + area = int(abs(area / 2.0)) 77 + 78 + # Calculate perimeter. 79 + perimeter = sum(a.dist_manhattan(b) for a, b in zip(points, points[1:] + [points[0]])) 80 + 81 + # Account for outer perimeter strip in final area computation. 82 + return area + (perimeter // 2) + 1 83 + 68 84 69 85 board = {} 70 86 for y, line in enumerate(fileinput.input()): ··· 82 98 break 83 99 84 100 85 - # TODO: Solve part 2 programmatically. 101 + # Solve part 2 by solving for the polygon area and 102 + # subtracting off all perimeter points. 103 + print("Part 2:", discrete_polygon_area(loop) - len(loop))