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.

Add solution for 2023/18

+56
+56
2023/day18.py
··· 1 + import fileinput 2 + from utils import Point, N, S, E, W 3 + 4 + DIR_MAPPING = { 5 + 'U': N, 6 + 'D': S, 7 + 'L': W, 8 + 'R': E, 9 + 10 + '0': E, 11 + '1': S, 12 + '2': W, 13 + '3': N, 14 + } 15 + 16 + def discrete_polygon_area(points): 17 + # Use shoelace formula to compute internal area. 18 + area = 0 19 + 20 + for a, b in zip(points, points[1:] + [points[0]]): 21 + area += (b.x + a.x) * (b.y - a.y) 22 + 23 + area = int(abs(area / 2.0)) 24 + 25 + # Calculate perimeter. 26 + perimeter = sum(a.dist_manhattan(b) for a, b in zip(points, points[1:] + [points[0]])) 27 + 28 + # Account for outer perimeter strip in final area computation. 29 + return area + (perimeter // 2) + 1 30 + 31 + 32 + # Parse problem input. 33 + p1_pos = Point(0, 0) 34 + p2_pos = Point(0, 0) 35 + 36 + p1_points = [p1_pos] 37 + p2_points = [p2_pos] 38 + 39 + for line in fileinput.input(): 40 + direction, distance, hex_code = line.split() 41 + p1_dir = DIR_MAPPING[direction] 42 + p1_dist = int(distance) 43 + 44 + p2_dir = DIR_MAPPING[hex_code[-2]] 45 + p2_dist = int(hex_code[2:-2], 16) 46 + 47 + p1_pos += p1_dir * p1_dist 48 + p2_pos += p2_dir * p2_dist 49 + 50 + p1_points.append(p1_pos) 51 + p2_points.append(p2_pos) 52 + 53 + 54 + # Solve problem. 55 + print("Part 1:", discrete_polygon_area(p1_points)) 56 + print("Part 2:", discrete_polygon_area(p2_points))