-
Notifications
You must be signed in to change notification settings - Fork 0
/
day3-1.groovy
44 lines (38 loc) · 1.1 KB
/
day3-1.groovy
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
sampleInput = '''467..114..
...*......
..35..633.
......#...
617*......
.....+.58.
..592.....
......755.
...$.*....
.664.598..
'''.split('\n') as List<String>
def input = new File('inputs/day3-1.txt').readLines()
PART_PATTERN = ~/[^\d\.]/
NUMBER_PATTERN = ~/\d+/
def solve(List<String> lines) {
def patterns = lines.withIndex().collectEntries { line, i ->
def positions = []
def matcher = line =~ PART_PATTERN
while (matcher.find()) {
positions << matcher.start()
}
[(i): positions]
}
lines.withIndex().sum { line, i ->
def suma = 0
def matcher = line =~ NUMBER_PATTERN
while (matcher.find()) {
if ((i > 0 && patterns[i-1].any { it >= matcher.start()-1 && it <= matcher.end() }) ||
patterns[i].any { it >= matcher.start()-1 && it <= matcher.end() } ||
(i+1 < lines.size() && patterns[i+1].any { it >= matcher.start()-1 && it <= matcher.end() })) {
suma += matcher.group() as long
}
}
suma
}
}
assert 4361 == solve(sampleInput)
println solve(input)