solution: day12

This commit is contained in:
Matej Janezic 2022-12-04 22:44:22 +01:00
parent 000002009f
commit 00000210a8
Signed by: janezicmatej
GPG Key ID: 4298E230ED37B2C0
4 changed files with 56 additions and 0 deletions

7
Cargo.lock generated
View File

@ -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"

View File

@ -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"

47
src/bin/12.rs Normal file
View File

@ -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::<i32>().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<u32> {
Some(parse_add(&parse(input).unwrap(), false) as u32)
}
pub fn part_two(input: &str) -> Option<u32> {
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));
}
}

1
src/test_inputs/12.txt Normal file
View File

@ -0,0 +1 @@
{"d":"red","e":[1,2,3,4],"f":5}