-
Notifications
You must be signed in to change notification settings - Fork 20
/
Copy pathDay9.java
84 lines (71 loc) · 1.88 KB
/
Day9.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
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
package com.sbaars.adventofcode.year16.days;
import com.sbaars.adventofcode.year16.Day2016;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Day9 extends Day2016 {
private static final Pattern MARKER_PATTERN = Pattern.compile("\\((\\d+)x(\\d+)\\)");
public Day9() {
super(9);
}
public static void main(String[] args) {
new Day9().printParts();
}
private long decompressV1(String input) {
long length = 0;
int pos = 0;
while (pos < input.length()) {
if (input.charAt(pos) == '(') {
Matcher m = MARKER_PATTERN.matcher(input.substring(pos));
if (m.find() && m.start() == 0) {
int chars = Integer.parseInt(m.group(1));
int repeat = Integer.parseInt(m.group(2));
pos += m.end();
length += (long) chars * repeat;
pos += chars;
} else {
length++;
pos++;
}
} else {
length++;
pos++;
}
}
return length;
}
private long decompressV2(String input) {
if (input.isEmpty()) {
return 0;
}
long length = 0;
int pos = 0;
while (pos < input.length()) {
if (input.charAt(pos) == '(') {
Matcher m = MARKER_PATTERN.matcher(input.substring(pos));
if (m.find() && m.start() == 0) {
int chars = Integer.parseInt(m.group(1));
int repeat = Integer.parseInt(m.group(2));
pos += m.end();
String repeatedSection = input.substring(pos, pos + chars);
length += decompressV2(repeatedSection) * repeat;
pos += chars;
} else {
length++;
pos++;
}
} else {
length++;
pos++;
}
}
return length;
}
@Override
public Object part1() {
return decompressV1(day().trim());
}
@Override
public Object part2() {
return decompressV2(day().trim());
}
}