-
Notifications
You must be signed in to change notification settings - Fork 20
/
Copy pathDay3.java
50 lines (41 loc) · 1.28 KB
/
Day3.java
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
package com.sbaars.adventofcode.year24.days;
import com.sbaars.adventofcode.year24.Day2024;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static java.lang.Integer.parseInt;
public class Day3 extends Day2024 {
public Day3() {
super(3);
}
public static void main(String[] args) {
new Day3().printParts();
}
@Override
public Object part1() {
return solve(day(), true);
}
@Override
public Object part2() {
return solve(day(), false);
}
private int solve(String input, boolean ignoreConditions) {
Pattern pattern = Pattern.compile("(mul\\((\\d+),(\\d+)\\))|(do\\(\\))|(don't\\(\\))");
Matcher matcher = pattern.matcher(input);
AtomicBoolean isEnabled = new AtomicBoolean(true);
return matcher.results()
.mapToInt(result -> {
if (result.group(1) != null && (ignoreConditions || isEnabled.get())) {
return parseInt(result.group(2)) * parseInt(result.group(3));
} else if (!ignoreConditions) {
if (result.group(4) != null) {
isEnabled.set(true);
} else if (result.group(5) != null) {
isEnabled.set(false);
}
}
return 0;
})
.sum();
}
}