feat: solve day 6

This commit is contained in:
Joshua Smallwood 2025-12-06 20:46:58 -06:00
parent a13fd2afe7
commit 1ccdf8d13d
2 changed files with 106 additions and 0 deletions

4
data/examples/06.txt Normal file
View file

@ -0,0 +1,4 @@
123 328 51 64
45 64 387 23
6 98 215 314
* + * +

102
src/bin/06.rs Normal file
View file

@ -0,0 +1,102 @@
use itertools::Itertools;
advent_of_code::solution!(6);
pub fn part_one(input: &str) -> Option<u64> {
let number_rows = input
.lines()
.filter(|line| {
!line.is_empty() && line.chars().find(|c| *c != ' ').unwrap_or(' ').is_numeric()
})
.map(|line| {
line.split(" ")
.filter(|s| !s.is_empty())
.map(|s| s.parse().unwrap_or(0))
.collect::<Vec<u64>>()
})
.collect::<Vec<Vec<u64>>>();
let operators = input
.lines()
.last()
.unwrap()
.split(" ")
.filter(|s| !s.is_empty());
operators
.enumerate()
.map(|(i, operator)| match operator {
"+" => number_rows.iter().map(|row| row[i]).sum(),
"*" => number_rows.iter().map(|row| row[i]).product(),
_ => 0,
})
.sum1()
}
pub fn part_two(input: &str) -> Option<u64> {
let operators = input
.lines()
.last()
.unwrap()
.split(" ")
.filter(|s| !s.is_empty());
let number_rows = input
.lines()
.filter(|line| {
!line.is_empty() && line.chars().find(|c| *c != ' ').unwrap_or(' ').is_numeric()
})
.map(|line| line.chars().collect())
.collect::<Vec<Vec<char>>>();
let width = input.lines().map(|line| line.len()).max().unwrap_or(0);
let height = input
.lines()
.filter(|line| {
!line.is_empty() && line.chars().find(|c| *c != ' ').unwrap_or(' ').is_numeric()
})
.count();
let mut chunks = vec![];
let mut curr_chunk = vec![];
for col in 0..width {
let mut chars = vec![];
for row in 0..height {
if col >= number_rows[row].len() {
chars.push(' ');
} else {
chars.push(number_rows[row][col]);
}
}
let num_str = chars.iter().join("");
if num_str.trim().is_empty() {
chunks.push(curr_chunk);
curr_chunk = vec![];
} else {
curr_chunk.push(num_str.trim().parse().unwrap());
}
}
chunks.push(curr_chunk);
operators
.enumerate()
.map(|(i, operator)| match operator {
"+" => chunks[i].iter().sum(),
"*" => chunks[i].iter().product(),
_ => 0,
})
.sum1()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_part_one() {
let result = part_one(&advent_of_code::template::read_file("examples", DAY));
assert_eq!(result, Some(4277556));
}
#[test]
fn test_part_two() {
let result = part_two(&advent_of_code::template::read_file("examples", DAY));
assert_eq!(result, Some(3263827));
}
}