diff --git a/Cargo.lock b/Cargo.lock index 2e12759..54bb767 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -197,6 +197,16 @@ dependencies = [ "nom", ] +[[package]] +name = "day09" +version = "0.1.0" +dependencies = [ + "aoc", + "color-eyre", + "nom", + "rayon", +] + [[package]] name = "either" version = "1.9.0" diff --git a/Cargo.toml b/Cargo.toml index 6fec940..4f812a4 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -9,5 +9,6 @@ members = [ "day04", "day05", "day06", + "day09", ] diff --git a/day09/Cargo.toml b/day09/Cargo.toml new file mode 100644 index 0000000..4fa788b --- /dev/null +++ b/day09/Cargo.toml @@ -0,0 +1,10 @@ +[package] +name = "day09" +version = "0.1.0" +edition = "2021" + +[dependencies] +aoc = { path = "../aoc" } +color-eyre = "0.6.2" +nom = "7.1.3" +rayon = "1.8.0" diff --git a/day09/src/bin/day09a.rs b/day09/src/bin/day09a.rs new file mode 100644 index 0000000..c23c2b5 --- /dev/null +++ b/day09/src/bin/day09a.rs @@ -0,0 +1,39 @@ +// Copyright (C) 2023 Leandro Lisboa Penz +// This file is subject to the terms and conditions defined in +// file 'LICENSE', which is part of this source code package. + +use rayon::prelude::*; +use std::io::{stdin, BufRead}; + +use day09::*; + +fn diffs(nums: &[i64]) -> Vec { + nums.par_windows(2).map(|l| l[1] - l[0]).collect() +} + +fn calc_next(nums: &Vec) -> i64 { + let mut lastsum = nums[nums.len() - 1]; + let mut currdiff = diffs(nums); + while !currdiff.par_iter().all(|n| n == &0) { + lastsum += currdiff[currdiff.len() - 1]; + currdiff = diffs(&currdiff); + } + lastsum +} + +fn process(bufin: impl BufRead) -> Result { + let input = parser::parse(bufin)?; + Ok(input.par_iter().map(calc_next).sum()) +} + +#[test] +fn test() -> Result<()> { + assert_eq!(process(EXAMPLE.as_bytes())?, 114); + Ok(()) +} + +fn main() -> Result<()> { + color_eyre::install()?; + println!("{}", process(stdin().lock())?); + Ok(()) +} diff --git a/day09/src/lib.rs b/day09/src/lib.rs new file mode 100644 index 0000000..2a3e3f2 --- /dev/null +++ b/day09/src/lib.rs @@ -0,0 +1,32 @@ +// Copyright (C) 2023 Leandro Lisboa Penz +// This file is subject to the terms and conditions defined in +// file 'LICENSE', which is part of this source code package. + +pub use color_eyre::{eyre::eyre, Result}; + +pub const EXAMPLE: &str = "0 3 6 9 12 15 +1 3 6 10 15 21 +10 13 16 21 30 45 +"; + +pub mod parser { + use aoc::parser::*; + + // use super::*; + + fn line(input: &str) -> IResult<&str, Vec> { + let (input, nums) = multi::separated_list1(character::space1, character::i64)(input)?; + let (input, _) = character::newline(input)?; + Ok((input, nums)) + } + + pub fn parse(mut bufin: impl BufRead) -> Result>> { + aoc::parse_with!(multi::many1(line), bufin) + } +} + +#[test] +fn test() -> Result<()> { + assert_eq!(parser::parse(EXAMPLE.as_bytes())?.len(), 3); + Ok(()) +}