Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 1df73fd

Browse files
Solve day 12 2015 part 2: JSAbacusFramework.io
1 parent f38dbe6 commit 1df73fd

File tree

1 file changed

+31
-16
lines changed
  • src/main/java/com/sbaars/adventofcode/year15/days

1 file changed

+31
-16
lines changed

‎src/main/java/com/sbaars/adventofcode/year15/days/Day12.java‎

Lines changed: 31 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -76,45 +76,60 @@ private int sumArray(String json) {
7676
}
7777

7878
private int sumObject(String json) {
79-
// Check if object contains "red" as a value
80-
Pattern redPattern = Pattern.compile(":\\s*\"red\"");
81-
Matcher redMatcher = redPattern.matcher(json);
82-
if (redMatcher.find()) {
83-
return 0;
84-
}
85-
8679
int sum = 0;
8780
int depth = 0;
8881
int start = 1;
8982
boolean inString = false;
83+
boolean hasRed = false;
84+
StringBuilder currentValue = new StringBuilder();
9085

9186
for (int i = 1; i < json.length() - 1; i++) {
9287
char c = json.charAt(i);
88+
9389
if (c == '"') {
90+
if (!inString && depth == 0) {
91+
currentValue.setLength(0);
92+
}
9493
inString = !inString;
94+
continue;
95+
}
96+
97+
if (inString) {
98+
currentValue.append(c);
99+
continue;
95100
}
96-
if (inString) continue;
97101

98102
if (c == '[' || c == '{') {
99103
depth++;
100104
} else if (c == ']' || c == '}') {
101105
depth--;
106+
} else if (c == ':' && depth == 0) {
107+
String value = currentValue.toString();
108+
currentValue.setLength(0);
109+
start = i + 1;
102110
} else if (c == ',' && depth == 0) {
103-
String part = json.substring(start, i).trim();
104-
int colonIndex = part.indexOf(':');
105-
if (colonIndex != -1) {
106-
sum += sumJson(part.substring(colonIndex + 1).trim());
111+
String value = json.substring(start, i).trim();
112+
if (value.equals("\"red\"")) {
113+
return 0;
114+
}
115+
if (!value.isEmpty()) {
116+
sum += sumJson(value);
107117
}
108118
start = i + 1;
109119
}
110120
}
121+
122+
// Process the last value
111123
if (start < json.length() - 1) {
112-
String part = json.substring(start, json.length() - 1).trim();
113-
int colonIndex = part.indexOf(':');
114-
if (colonIndex != -1) {
115-
sum += sumJson(part.substring(colonIndex + 1).trim());
124+
String value = json.substring(start, json.length() - 1).trim();
125+
if (value.equals("\"red\"")) {
126+
return 0;
127+
}
128+
if (!value.isEmpty()) {
129+
sum += sumJson(value);
116130
}
117131
}
132+
118133
return sum;
119134
}
120135
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /