-
Notifications
You must be signed in to change notification settings - Fork 0
/
a05.py
92 lines (74 loc) · 1.99 KB
/
a05.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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
example = """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"""
f = open("input/05.input")
text = f.read().strip()
def parse(t):
res = []
for line in t.split("\n"):
left, right = line.split(" -> ")
left = [int(n) for n in left.split(',')]
right = [int(n) for n in right.split(',')]
res.append((left, right))
return res
def part1(text):
parsed = parse(text)
overlap = set()
seen = set()
for line in parsed:
x1, y1 = line[0]
x2, y2 = line[1]
if x1 == x2:
for y in range(min(y1, y2), max(y1, y2) + 1):
if (x1, y) in seen:
overlap.add((x1, y))
seen.add((x1, y))
elif y1 == y2:
for x in range(min(x1, x2), max(x1, x2) + 1):
if (x, y1) in seen:
overlap.add((x, y1))
seen.add((x, y1))
return len(overlap)
def part2(text):
parsed = parse(text)
overlap = set()
seen = set()
for line in parsed:
x1, y1 = line[0]
x2, y2 = line[1]
if x1 == x2:
for y in range(min(y1, y2), max(y1, y2) + 1):
if (x1, y) in seen:
overlap.add((x1, y))
seen.add((x1, y))
elif y1 == y2:
for x in range(min(x1, x2), max(x1, x2) + 1):
if (x, y1) in seen:
overlap.add((x, y1))
seen.add((x, y1))
else:
if x1 > x2:
tmp = x2, y2
x2, y2 = x1, y1
x1, y1 = tmp
dy = 1 if y1 < y2 else -1
y = y1
for x in range(x1, x2 + 1):
if (x, y) in seen:
overlap.add((x, y))
seen.add((x, y))
y += dy
return len(overlap)
def main(text):
print("Part1:", part1(text))
print("Part2:", part2(text))
main(example)
print()
main(text)