2023-09: Solve part 2

This commit is contained in:
Mathis 2023-12-20 23:18:31 +01:00
parent cd66aca007
commit 793241a355
4 changed files with 46 additions and 19 deletions

View File

@ -0,0 +1,11 @@
pub fn parse_line(s: &str) -> Vec<i32> {
s.split_whitespace().map(|x| x.parse().unwrap()).collect()
}
pub fn get_differences(nums: Vec<i32>) -> Vec<i32> {
nums.windows(2).map(|w| w[1] - w[0]).collect()
}
pub fn all_zeros(nums: Vec<i32>) -> bool {
nums.iter().all(|&x| x == 0)
}

View File

@ -1,5 +1,6 @@
pub mod part_one;
// pub mod part_two;
pub mod part_two;
pub mod common;
use crate::utils::solution::Solution;
use crate::utils::input_reader;
@ -8,16 +9,12 @@ use crate::utils::input_reader;
pub struct Day9Solution;
impl Solution for Day9Solution {
fn part_one(&self) -> String {
// Implementation for part one of day 1
// ...
input_reader::read_input_file("input/2023/day_09/input.txt", part_one::part_one)
}
fn part_two(&self) -> String {
// Implementation for part two of day 1
// ...
String::from("Not implemented")
// part_two::part_two()
input_reader::read_input_file("input/2023/day_09/input.txt", part_two::part_two)
}
}

View File

@ -1,3 +1,5 @@
use super::common::{parse_line, get_differences, all_zeros};
pub fn part_one(input_lines: Vec<String>) -> String {
let mut result: i32 = 0;
@ -19,16 +21,4 @@ pub fn part_one(input_lines: Vec<String>) -> String {
}
result.to_string()
}
fn parse_line(s: &str) -> Vec<i32> {
s.split_whitespace().map(|x| x.parse().unwrap()).collect()
}
fn get_differences(nums: Vec<i32>) -> Vec<i32> {
nums.windows(2).map(|w| w[1] - w[0]).collect()
}
fn all_zeros(nums: Vec<i32>) -> bool {
nums.iter().all(|&x| x == 0)
}

View File

@ -0,0 +1,29 @@
use super::common::{parse_line, get_differences, all_zeros};
pub fn part_two(input_lines: Vec<String>) -> String {
let mut result: i32 = 0;
for line in input_lines {
let nums = parse_line(&line);
let mut first: Vec<i32> = Vec::new();
first.push(nums.first().unwrap().clone());
let mut diffs = get_differences(nums.clone());
first.push(diffs.first().unwrap().clone());
while !all_zeros(diffs.clone()) {
diffs = get_differences(diffs.clone());
first.push(diffs.first().unwrap().clone());
}
first.reverse();
let mut res = 0;
res = first.iter().fold(res, |acc, &x| x - acc);
result += res;
}
result.to_string()
}