2015 day 12

This commit is contained in:
dece 2021-11-08 20:54:57 +01:00
parent 471a3064ad
commit ac605225d5
3 changed files with 73 additions and 0 deletions

32
2015/Cargo.lock generated
View file

@ -1,14 +1,46 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 3
[[package]]
name = "aoc2015"
version = "0.1.0"
dependencies = [
"md5",
"serde_json",
]
[[package]]
name = "itoa"
version = "0.4.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b71991ff56294aa922b450139ee08b3bfc70982c6b2c7562771375cf73542dd4"
[[package]]
name = "md5"
version = "0.7.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "490cc448043f947bae3cbee9c203358d62dbee0db12107a74be5c30ccfd09771"
[[package]]
name = "ryu"
version = "1.0.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "71d301d4193d031abdd79ff7e3dd721168a9572ef3fe51a1517aba235bd8f86e"
[[package]]
name = "serde"
version = "1.0.130"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f12d06de37cf59146fbdecab66aa99f9fe4f78722e3607577a5375d66bd0c913"
[[package]]
name = "serde_json"
version = "1.0.69"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e466864e431129c7e0d3476b92f20458e5879919a0596c6472738d9fa2d342f8"
dependencies = [
"itoa",
"ryu",
"serde",
]

View file

@ -9,3 +9,4 @@ name = "aoc"
[dependencies]
md5 = "0.7.0"
serde_json = "1.0.69"

40
2015/src/bin/day12.rs Normal file
View file

@ -0,0 +1,40 @@
use serde_json::{self, Value};
use aoc::input;
fn main() {
let json: Value = serde_json::from_str(&input::read_chars()).unwrap();
// Part 1
let sum_num = sum_numbers(&json);
println!("Sum of numbers: {}", sum_num);
// Part 2
let sum_num_2 = sum_numbers_2(&json);
println!("Sum of un-red numbers: {}", sum_num_2);
}
fn sum_numbers(value: &Value) -> i64 {
match value {
Value::Number(number) => number.as_i64().unwrap(),
Value::Array(array) => array.iter().map(|v| sum_numbers(v)).sum(),
Value::Object(map) => map.values().map(|v| sum_numbers(v)).sum(),
_ => 0,
}
}
fn sum_numbers_2(value: &Value) -> i64 {
match value {
Value::Number(number) => number.as_i64().unwrap(),
Value::Array(array) => array.iter().map(|v| sum_numbers_2(v)).sum(),
Value::Object(map) => {
for str_prop in map.values().map(|p| p.as_str()) {
if str_prop == Some("red") {
return 0;
}
}
map.values().map(|v| sum_numbers_2(v)).sum()
}
_ => 0,
}
}