2025/day-06: Solve part 2

This commit is contained in:
SebastianStork 2025-12-06 23:48:36 +01:00
parent 5bb9bcc7b3
commit e3b750544f
Signed by: SebastianStork
SSH key fingerprint: SHA256:tRrGdjYOwgHxpSc/wTOZQZEjxcb15P0tyXRsbAfd+2Q

View file

@ -1,4 +1,4 @@
use std::{fmt::Debug, fs};
use std::{fmt::Debug, fs, str::FromStr};
#[derive(PartialEq, Debug)]
enum Operation {
@ -6,6 +6,18 @@ enum Operation {
Multiply,
}
impl FromStr for Operation {
type Err = ();
fn from_str(input: &str) -> Result<Operation, Self::Err> {
match input {
"+" => Ok(Operation::Add),
"*" => Ok(Operation::Multiply),
_ => Err(()),
}
}
}
#[derive(Debug)]
struct Problem {
numbers: Vec<u64>,
@ -14,46 +26,79 @@ struct Problem {
impl Problem {
fn solve(&self) -> u64 {
if self.operation == Operation::Add {
self.numbers.iter().sum()
} else {
self.numbers.iter().product()
match self.operation {
Operation::Add => self.numbers.iter().sum(),
Operation::Multiply => self.numbers.iter().product(),
}
}
}
fn main() {
let problems = parse_input(&fs::read_to_string("../../inputs/06.txt").unwrap());
let content = &mut fs::read_to_string("../../inputs/06.txt").unwrap();
println!("Grand total: {}", grand_total(&problems));
println!("Grand total 1: {}", grand_total(&parse_input_v1(content)));
println!("Grand total 2: {}", grand_total(&parse_input_v2(content)));
}
fn parse_input(contents: &str) -> Vec<Problem> {
fn parse_input_v1(contents: &str) -> Vec<Problem> {
let grid: Vec<Vec<&str>> = contents
.trim()
.lines()
.map(|line| line.split_whitespace().collect())
.collect();
let mut list: Vec<Problem> = Vec::new();
let operations_row = grid.last().unwrap();
let num_cols = grid[0].len();
for (col, _) in grid[0].iter().enumerate() {
let mut numbers: Vec<u64> = Vec::new();
(0..num_cols)
.map(|col_index| {
let operation = Operation::from_str(operations_row[col_index]).unwrap();
let operation = match grid[grid.len() - 1][col] {
"+" => Operation::Add,
"*" => Operation::Multiply,
_ => panic!("Unsupported Operation"),
};
let numbers = grid[..grid.len() - 1]
.iter()
.map(|row| row[col_index].parse().unwrap())
.collect();
for (row, _) in grid[..grid.len() - 1].iter().enumerate() {
numbers.push(grid[row][col].parse().unwrap());
Problem { numbers, operation }
})
.collect()
}
list.push(Problem { numbers, operation });
fn parse_input_v2(contents: &str) -> Vec<Problem> {
let grid: Vec<Vec<u8>> = contents
.trim_end_matches('\n')
.lines()
.map(|line| line.as_bytes().to_vec())
.collect();
let operations_row = grid.last().unwrap();
let mut problems = Vec::new();
let mut numbers = Vec::new();
let mut operation = Operation::Add;
for col in 0..grid[0].len() {
if let Ok(op) = Operation::from_str(&(operations_row[col] as char).to_string()) {
operation = op;
}
list
let column: String = (0..grid.len() - 1)
.map(|row| grid[row][col] as char)
.filter(|c| !c.is_whitespace())
.collect();
if column.is_empty() {
problems.push(Problem { numbers, operation });
numbers = Vec::new();
operation = Operation::Add;
} else {
numbers.push(column.parse().unwrap());
}
}
problems.push(Problem { numbers, operation });
problems
}
fn grand_total(problems: &[Problem]) -> u64 {
@ -64,14 +109,19 @@ fn grand_total(problems: &[Problem]) -> u64 {
mod tests {
use super::*;
const TEST_INPUT: &str = "
123 328 51 64
const TEST_INPUT: &str = "123 328 51 64
45 64 387 23
6 98 215 314
* + * + ";
* + * +
";
#[test]
fn test_part1() {
assert_eq!(grand_total(&parse_input(TEST_INPUT)), 4277556);
assert_eq!(grand_total(&parse_input_v1(TEST_INPUT)), 4277556);
}
#[test]
fn test_part2() {
assert_eq!(grand_total(&parse_input_v2(TEST_INPUT)), 3263827);
}
}