day-07 part-2

This commit is contained in:
Kristofers Solo 2024-12-07 12:01:09 +02:00
parent c2eb41f435
commit acfbcbea08
5 changed files with 123 additions and 22 deletions

View File

@ -1,10 +0,0 @@
....#.....
.........#
..........
..#.......
.......#..
..........
.#..^.....
........#.
#.........
......#...

View File

@ -7,6 +7,6 @@ fn main() -> Result<()> {
let file = include_str!("../../input1.txt"); let file = include_str!("../../input1.txt");
let result = process(file).context("process part 1")?; let result = process(file).context("process part 1")?;
println!("{}", result); println!("{result}");
Ok(()) Ok(())
} }

View File

@ -7,6 +7,6 @@ fn main() -> Result<()> {
let file = include_str!("../../input2.txt"); let file = include_str!("../../input2.txt");
let result = process(file).context("process part 2")?; let result = process(file).context("process part 2")?;
println!("{}", result); println!("{result}");
Ok(()) Ok(())
} }

View File

@ -1,8 +1,6 @@
use std::str::FromStr;
use miette::{Diagnostic, Result}; use miette::{Diagnostic, Result};
use std::str::FromStr;
use thiserror::Error; use thiserror::Error;
use tracing::Instrument;
#[derive(Debug, Clone, Copy)] #[derive(Debug, Clone, Copy)]
enum Operator { enum Operator {
@ -11,7 +9,7 @@ enum Operator {
} }
impl Operator { impl Operator {
const fn apply(&self, a: usize, b: usize) -> usize { const fn apply(self, a: usize, b: usize) -> usize {
match self { match self {
Self::Add => a + b, Self::Add => a + b,
Self::Multiply => a * b, Self::Multiply => a * b,

View File

@ -1,9 +1,115 @@
use miette::Result; use miette::{Diagnostic, Result};
use std::str::FromStr;
use thiserror::Error;
#[derive(Debug, Clone, Copy)]
enum Operator {
Add,
Multiply,
Concatenation,
}
impl Operator {
fn apply(self, a: usize, b: usize) -> usize {
match self {
Self::Add => a + b,
Self::Multiply => a * b,
Self::Concatenation => format!("{a}{b}").parse::<usize>().unwrap(),
}
}
const fn all_operators() -> [Self; 3] {
[Self::Add, Self::Multiply, Self::Concatenation]
}
}
#[derive(Debug, Error, Diagnostic)]
enum EquationError {
#[error("Failed to parse equation")]
ParseError,
#[error("Missing value")]
MissingValue,
}
#[derive(Debug)]
struct Equation {
result: usize,
numbers: Vec<usize>,
}
impl Equation {
fn find_result(&self) -> Option<usize> {
fn recursive_find(
numbers: &[usize],
target: usize,
current: usize,
index: usize,
is_first: bool,
) -> Option<usize> {
if index == numbers.len() {
return if current == target {
Some(current)
} else {
None
};
}
let num = numbers[index];
for op in Operator::all_operators() {
if let Some(result) = recursive_find(
numbers,
target,
if is_first {
num
} else {
op.apply(current, num)
},
index + 1,
false,
) {
return Some(result);
}
}
None
}
if self.numbers.is_empty() {
return None;
}
recursive_find(&self.numbers, self.result, 0, 0, true)
}
}
impl FromStr for Equation {
type Err = EquationError;
fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
let line = s.trim().split(':').collect::<Vec<_>>();
let result = line
.first()
.ok_or(EquationError::MissingValue)?
.parse()
.map_err(|_| EquationError::ParseError)?;
let numbers = line
.last()
.ok_or(EquationError::MissingValue)?
.split_whitespace()
.map(str::parse)
.collect::<Result<Vec<usize>, _>>()
.map_err(|_| EquationError::ParseError)?;
Ok(Self { result, numbers })
}
}
#[tracing::instrument] #[tracing::instrument]
pub fn process(input: &str) -> Result<usize> { pub fn process(input: &str) -> Result<usize> {
todo!("day xx - part 2"); let result = input
Ok(0) .lines()
.map(Equation::from_str)
.filter_map(|eq| eq.ok()?.find_result())
.sum();
Ok(result)
} }
#[cfg(test)] #[cfg(test)]
@ -12,9 +118,16 @@ mod tests {
#[test] #[test]
fn test_process() -> Result<()> { fn test_process() -> Result<()> {
let input = ""; let input = "190: 10 19
todo!("haven't built test yet"); 3267: 81 40 27
let result = 0; 83: 17 5
156: 15 6
7290: 6 8 6 15
161011: 16 10 13
192: 17 8 14
21037: 9 7 18 13
292: 11 6 16 20";
let result = 11387;
assert_eq!(process(input)?, result); assert_eq!(process(input)?, result);
Ok(()) Ok(())
} }