Day 12 part 2.

This commit is contained in:
2024-01-12 17:00:54 +01:00
parent 41dc08ca98
commit 0fed13a332
3 changed files with 36 additions and 1 deletions

View File

@@ -1,4 +1,5 @@
use aoc_runner_derive::aoc;
use json::{parse, JsonValue};
use regex::Regex;
#[aoc(day12, part1)]
@@ -10,6 +11,32 @@ fn part1(input: &str) -> i64 {
.sum()
}
#[aoc(day12, part2)]
fn part2(input: &str) -> i64 {
let json = parse(input).unwrap();
sum(&json)
}
fn sum(json: &JsonValue) -> i64 {
match json {
JsonValue::Null => 0,
JsonValue::Short(_) => 0,
JsonValue::String(_) => 0,
JsonValue::Number(_) => json.as_i64().unwrap(),
JsonValue::Boolean(_) => 0,
JsonValue::Object(o) => {
if o.iter().any(|(_, value)| {
value.is_string() && Some("red") == value.as_str()
}) {
0
} else {
o.iter().map(|(_key, value)| sum(value)).sum()
}
}
JsonValue::Array(a) => a.iter().map(|e| sum(e)).sum(),
}
}
#[cfg(test)]
mod tests {
use super::*;