Skip to content

Commit

Permalink
Day 09a
Browse files Browse the repository at this point in the history
  • Loading branch information
lpenz committed Dec 9, 2023
1 parent cbf16ba commit a910ddb
Show file tree
Hide file tree
Showing 5 changed files with 92 additions and 0 deletions.
10 changes: 10 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -9,5 +9,6 @@ members = [
"day04",
"day05",
"day06",
"day09",
]

10 changes: 10 additions & 0 deletions day09/Cargo.toml
Original file line number Diff line number Diff line change
@@ -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"
39 changes: 39 additions & 0 deletions day09/src/bin/day09a.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
// Copyright (C) 2023 Leandro Lisboa Penz <lpenz@lpenz.org>
// 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<i64> {
nums.par_windows(2).map(|l| l[1] - l[0]).collect()
}

fn calc_next(nums: &Vec<i64>) -> 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<i64> {
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(())
}
32 changes: 32 additions & 0 deletions day09/src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
// Copyright (C) 2023 Leandro Lisboa Penz <lpenz@lpenz.org>
// 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<i64>> {
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<Vec<Vec<i64>>> {
aoc::parse_with!(multi::many1(line), bufin)
}
}

#[test]
fn test() -> Result<()> {
assert_eq!(parser::parse(EXAMPLE.as_bytes())?.len(), 3);
Ok(())
}

0 comments on commit a910ddb

Please sign in to comment.