diff --git a/Cargo.lock b/Cargo.lock index 55fc363..643445c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -30,6 +30,7 @@ dependencies = [ "hashbrown 0.13.1", "hex-literal", "itertools", + "json", "lazy_static", "pico-args", "regex", @@ -394,6 +395,12 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "json" +version = "0.12.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "078e285eafdfb6c4b434e0d31e8cfcb5115b651496faca5749b88fafd4f23bfd" + [[package]] name = "lazy_static" version = "1.4.0" diff --git a/Cargo.toml b/Cargo.toml index 0b40970..885e376 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -12,6 +12,7 @@ dotenv = "0.15.0" hashbrown = "0.13.1" hex-literal = "0.3.4" itertools = "0.10.5" +json = "0.12.4" lazy_static = "1.4.0" pico-args = "0.5.0" regex = "1.7.0" diff --git a/src/bin/12.rs b/src/bin/12.rs new file mode 100644 index 000000000..24fb47d --- /dev/null +++ b/src/bin/12.rs @@ -0,0 +1,47 @@ +use json::{parse, JsonValue::*, JsonValue}; + +fn parse_add(json_object: &JsonValue, skip_red: bool) -> i32 { + match json_object { + Number(x) => x.to_string().parse::().unwrap_or(0), + Object(x) => { + if skip_red { + for (_, node) in x.iter() { + if let Short { .. } = node { + if node.as_str() == Some("red") { + return 0; + } + } + } + } + x.iter().map(|(_, x)| parse_add(x, skip_red)).sum() + } + Array(x) => x.iter().map(|y| parse_add(y, skip_red)).sum(), + _ => 0, + } +} + +pub fn part_one(input: &str) -> Option { + Some(parse_add(&parse(input).unwrap(), false) as u32) +} +pub fn part_two(input: &str) -> Option { + Some(parse_add(&parse(input).unwrap(), true) as u32) +} +fn main() { + let input = &aoc::read_file("inputs", 12); + aoc::solve!(1, part_one, input); + aoc::solve!(2, part_two, input); +} +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn test_part_one() { + let input = aoc::read_file("test_inputs", 12); + assert_eq!(part_one(&input.trim()), Some(15)); + } + #[test] + fn test_part_two() { + let input = aoc::read_file("test_inputs", 12); + assert_eq!(part_two(&input.trim()), Some(0)); + } +} diff --git a/src/test_inputs/12.txt b/src/test_inputs/12.txt new file mode 100644 index 000000000..0fe6b51 --- /dev/null +++ b/src/test_inputs/12.txt @@ -0,0 +1 @@ +{"d":"red","e":[1,2,3,4],"f":5}