Repository navigation
Expand file tree
/
Copy pathday05.py
More file actions
80 lines (56 loc) · 1.54 KB
/
Copy pathday05.py
File metadata and controls
80 lines (56 loc) · 1.54 KB
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
from collections import defaultdict
from itertools import repeat
from typing import Tuple
import parse
from run_util import run_puzzle
Point = Tuple[int, int]
def parse_data(data):
numbers = [parse.parse('{:d},{:d} -> {:d},{:d}', line).fixed for line in data.split('\n')]
return [((x1, y1), (x2, y2)) for x1, y1, x2, y2 in numbers]
def get_gen(x1, x2):
if x1 == x2:
return repeat(x1)
step = -1 if x1 > x2 else 1
return range(x1, x2 + step, step)
def get_points(p1: Point, p2: Point, allow_diagonal=False):
x1, y1 = p1
x2, y2 = p2
if not allow_diagonal:
if x1 != x2 and y1 != y2:
return []
x_gen = get_gen(x1, x2)
y_gen = get_gen(y1, y2)
return zip(x_gen, y_gen)
def part_a(data):
lines = parse_data(data)
map = defaultdict(int)
for start, end in lines:
for point in get_points(start, end):
map[point] += 1
count = len([x for x in map.values() if x >= 2])
return count
def part_b(data):
lines = parse_data(data)
map = defaultdict(int)
for start, end in lines:
for point in get_points(start, end, allow_diagonal=True):
map[point] += 1
count = len([x for x in map.values() if x >= 2])
return count
def main():
examples = [
("""0,9 -> 5,9
8,0 -> 0,8
9,4 -> 3,4
2,2 -> 2,1
7,0 -> 7,4
6,4 -> 2,0
0,9 -> 2,9
3,4 -> 1,4
0,0 -> 8,8
5,5 -> 8,2""", 5, 12)
]
day = int(__file__.split('/')[-1].split('.')[0][-2:])
run_puzzle(day, part_a, part_b, examples)
if __name__ == '__main__':
main()