repl.it
@21natzil/

Day 3

Python

Wire intersections

fork
loading
Files
  • main.py
  • wires.txt
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
from collections import OrderedDict
from time import time

with open("wires.txt") as f:
  wires = [wire.split(',') for wire in f]

def create_grid(wire):
  starting = [0, 0]
  grid = OrderedDict()
  for line in wire:
    code, dist = line[0], int(line[1:])
    if code == 'U':
      starting[1] += dist
    elif code == 'D':
      starting[1] -= dist
    elif code == 'R':
      starting[0] += dist
    elif code == 'L':
      starting[0] -= dist
    else:
      print("Wrong code for grid!")
    grid[tuple(starting)] = code, dist
  return grid

def create_lines(grid):
  for point, (code, dist) in grid.items():
    if code == 'U':
      points = set((point[0], point[1] - i) for i in range(dist))
      mapping = {(point[0], point[1] - i): dist - i for i in range(dist)}
    elif code == 'D':
      points = set((point[0], point[1] + i) for i in range(dist))
      mapping = {(point[0], point[1] + i): dist - i for i in range(dist)}
    elif code == 'R':
      points = set((point[0] - i, point[1]) for i in range(dist))
      mapping = {(point[0] - i, point[1]): dist - i for i in range(dist)}
    elif code == 'L':
      points = set((point[0] + i, point[1]) for i in range(dist))
      mapping = {(point[0] + i, point[1]): dist - i for i in range(dist)}
    else:
      print("Wrong code for intersection")
    yield points, mapping

start_time = time()

first_grid = create_grid(wires[0])
second_grid = create_grid(wires[1])
total_points = {}

first_len = 0
for first_line, first_map in create_lines(first_grid):
  second_len = 0
  for second_line, second_map in create_lines(second_grid):
    intersections = first_line & second_line
    for intersection in intersections:
      total_points[intersection] = first_len + second_len + first_map[intersection] + second_map[intersection]
    second_len += len(second_line)
  first_len += len(first_line)


closest = min(total_points.keys(), key=lambda x: sum(map(abs, x)))

print("Day 1:", abs(closest[0]) + abs(closest[1]))
print("Day 2:", min(total_points.values()))
print("Took", time() - start_time, "seconds")