Skip to content

Commit

Permalink
Day 09b
Browse files Browse the repository at this point in the history
  • Loading branch information
lpenz committed Dec 9, 2023
1 parent a910ddb commit 1cb36a2
Show file tree
Hide file tree
Showing 4 changed files with 43 additions and 5 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
![AoC](https://img.shields.io/badge/AoC%20%E2%AD%90-12-yellow)
![AoC](https://img.shields.io/badge/AoC%20%E2%AD%90-14-yellow)
[![CI](https://github.com/lpenz/adventofcode2023/workflows/CI/badge.svg)](https://github.com/lpenz/adventofcode2023/actions)
[![coveralls](https://coveralls.io/repos/github/lpenz/adventofcode2023/badge.svg?branch=main)](https://coveralls.io/github/lpenz/adventofcode2023?branch=main)

Expand Down
4 changes: 0 additions & 4 deletions day09/src/bin/day09a.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,6 @@ 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);
Expand Down
37 changes: 37 additions & 0 deletions day09/src/bin/day09b.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
// 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 calc_prev(nums: &[i64]) -> i64 {
let mut mult = -1;
let mut result = nums[0];
let mut currdiff = diffs(nums);
while !currdiff.par_iter().all(|n| n == &0) {
result += mult * currdiff[0];
mult *= -1;
currdiff = diffs(&currdiff);
}
result
}

fn process(bufin: impl BufRead) -> Result<i64> {
let input = parser::parse(bufin)?;
Ok(input.par_iter().map(|v| calc_prev(v)).sum())
}

#[test]
fn test() -> Result<()> {
assert_eq!(process(EXAMPLE.as_bytes())?, 2);
Ok(())
}

fn main() -> Result<()> {
color_eyre::install()?;
println!("{}", process(stdin().lock())?);
Ok(())
}
5 changes: 5 additions & 0 deletions day09/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
// file 'LICENSE', which is part of this source code package.

pub use color_eyre::{eyre::eyre, Result};
use rayon::prelude::*;

pub const EXAMPLE: &str = "0 3 6 9 12 15
1 3 6 10 15 21
Expand All @@ -25,6 +26,10 @@ pub mod parser {
}
}

pub fn diffs(nums: &[i64]) -> Vec<i64> {
nums.par_windows(2).map(|l| l[1] - l[0]).collect()
}

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

0 comments on commit 1cb36a2

Please sign in to comment.