This commit is contained in:
Kristofers Solo
2023-12-09 16:05:09 +02:00
parent ed4438c3f7
commit 038214af40
9 changed files with 532 additions and 0 deletions

View File

@@ -0,0 +1,9 @@
use color_eyre::Result;
use day_09::part1::process;
fn main() -> Result<()> {
let file = include_str!("../../input1.txt");
let result = process(file)?;
println!("{}", result);
Ok(())
}

View File

@@ -0,0 +1,9 @@
use color_eyre::Result;
use day_09::part2::process;
fn main() -> Result<()> {
let file = include_str!("../../input2.txt");
let result = process(file)?;
println!("{}", result);
Ok(())
}

2
2023/day-09/src/lib.rs Normal file
View File

@@ -0,0 +1,2 @@
pub mod part1;
pub mod part2;

46
2023/day-09/src/part1.rs Normal file
View File

@@ -0,0 +1,46 @@
use color_eyre::Result;
use itertools::{Itertools, Position};
fn process_line(line: &str) -> i64 {
let mut nums = line
.split_whitespace()
.map(|num| num.parse::<i64>().unwrap())
.collect::<Vec<_>>();
let mut end_nums = Vec::new();
while !nums.iter().all(|num| num == &0) {
nums = nums
.iter()
.tuple_windows()
.with_position()
.map(|(pos, (left, right))| {
if let Position::Last | Position::Only = pos {
end_nums.push(*right)
}
right - left
})
.collect()
}
end_nums.iter().sum()
}
pub fn process(input: &str) -> Result<i64> {
let total = input.lines().map(process_line).sum();
Ok(total)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_process() -> Result<()> {
let input = "0 3 6 9 12 15
1 3 6 10 15 21
10 13 16 21 30 45";
assert_eq!(114, process(input)?);
Ok(())
}
}

48
2023/day-09/src/part2.rs Normal file
View File

@@ -0,0 +1,48 @@
use color_eyre::Result;
use itertools::{Itertools, Position};
fn process_line(line: &str) -> i64 {
let mut nums = line
.split_whitespace()
.map(|num| num.parse::<i64>().unwrap())
.collect::<Vec<_>>();
let mut start_nums = Vec::new();
while !nums.iter().all(|num| num == &0) {
nums = nums
.iter()
.tuple_windows()
.with_position()
.map(|(pos, (left, right))| {
if let Position::First | Position::Only = pos {
start_nums.push(*left)
}
right - left
})
.collect()
}
dbg!(&start_nums);
let result = start_nums.iter().rev().fold(0, |acc, num| num - acc);
result
}
pub fn process(input: &str) -> Result<i64> {
let total = input.lines().map(process_line).sum();
Ok(total)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_process() -> Result<()> {
let input = "0 3 6 9 12 15
1 3 6 10 15 21
10 13 16 21 30 45";
assert_eq!(2, process(input)?);
Ok(())
}
}