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

7
Cargo.lock generated
View File

@@ -8,6 +8,7 @@ version = "0.1.0"
dependencies = [
"aoc-runner",
"aoc-runner-derive",
"json",
"regex",
]
@@ -55,6 +56,12 @@ version = "0.4.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1306f3464951f30e30d12373d31c79fbd52d236e5e896fd92f96ec7babbbe60b"
[[package]]
name = "json"
version = "0.12.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "078e285eafdfb6c4b434e0d31e8cfcb5115b651496faca5749b88fafd4f23bfd"
[[package]]
name = "memchr"
version = "2.7.1"

View File

@@ -11,3 +11,4 @@ bench = false
aoc-runner = "0.3.0"
aoc-runner-derive = "0.3.0"
regex = "1.10.2"
json = "0.12.4"

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::*;