-
Notifications
You must be signed in to change notification settings - Fork 0
/
day3.py
96 lines (77 loc) · 2.02 KB
/
day3.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
93
94
95
import unittest
import re
def parseInput(input):
return list(input.splitlines())
def hasCloseSymbol(lines, li, l, r):
line = lines[li]
width = len(line)
nb_lines = len(lines)
for i in range(max(0, l - 1), min(width, r + 1)):
for j in range(max(0, li - 1), min(nb_lines, li + 2)):
if re.match(r'[^\d.]', lines[j][i]):
return True
return False
def parse1(input):
lines = parseInput(input)
result = 0
for li in range(0, len(lines)):
for m in re.finditer(r'(\d+)', lines[li]):
n = int(m.group())
if hasCloseSymbol(lines, li, m.start(), m.end()):
result += n
return result
def parseNumbers(line):
numbers = []
for m in re.finditer(r'(\d+)', line):
numbers.append((
int(m.group()),
m.start(),
m.end() - 1
))
return numbers
def closeNumbers(numbers, x, y):
result = []
for i in range(max(0, y - 1), min(len(numbers), y + 2)):
ns = numbers[i]
for n, j, k in ns:
if j - 1 <= x and x <= k + 1:
result.append(n)
return result
def parse2(input):
lines = parseInput(input)
numbers = list(map(parseNumbers, lines))
result = 0
for li in range(0, len(lines)):
for m in re.finditer(r'\*', lines[li]):
ns = closeNumbers(numbers, m.start(), li)
if len(ns) == 2:
result += ns[0] * ns[1]
return result
class Test(unittest.TestCase):
def test_part1(self):
self.assertEqual(parse1("""467..114..
...*......
..35..633.
......#...
617*......
.....+.58.
..592.....
......755.
...$.*....
.664.598.."""), 4361)
def test_part2(self):
self.assertEqual(parse2("""467..114..
...*......
..35..633.
......#...
617*......
.....+.58.
..592.....
......755.
...$.*....
.664.598.."""), 467835)
unittest.main(exit=False)
with open('input3.txt') as file:
data = file.read()
print("Part 1:", parse1(data))
print("Part 2:", parse2(data))