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.

at main 56 lines 1.2 kB view raw
1import fileinput 2from utils import Point, N, S, E, W 3 4DIR_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 16def 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. 33p1_pos = Point(0, 0) 34p2_pos = Point(0, 0) 35 36p1_points = [p1_pos] 37p2_points = [p2_pos] 38 39for 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. 55print("Part 1:", discrete_polygon_area(p1_points)) 56print("Part 2:", discrete_polygon_area(p2_points))