Break day 7 into modules

This commit is contained in:
2025-06-16 11:32:05 -05:00
parent 0b6ff3a4d0
commit b0a81013bd
3 changed files with 115 additions and 105 deletions

85
day_07/src/equation.rs Normal file
View File

@@ -0,0 +1,85 @@
mod operator_set;
use operator_set::create_operator_set;
#[derive(Debug, Clone, Copy)]
enum Ops {
Multiply,
Add,
}
#[derive(Debug)]
pub struct Equation {
answer: i64,
components: Vec<i64>,
}
impl Equation {
/// Create a new Equation from a string like:
///
/// Answer: components
/// 190: 10 19
pub fn new(equation_str: &str) -> Result<Equation, String> {
// Split answer and components
let split_equation: Vec<_> = equation_str.split(":").collect();
if split_equation.len() != 2 {
return Err(format!("Invalid equation string: {}", equation_str));
}
let answer = match split_equation[0].parse() {
Ok(a) => a,
Err(_) => {
return Err(format!(
"Error parsing answer {} in equation: {}",
split_equation[0], equation_str
));
}
};
// Parse components
let components = split_equation[1]
.split_whitespace()
.map(|c| match c.parse::<i64>() {
Ok(a) => Ok(a),
Err(_) => Err(format!(
"Error parsing component {} in equation: {}",
c, equation_str
)),
})
.collect::<Result<Vec<i64>, String>>()?;
Ok(Equation { answer, components })
}
pub fn answer(&self) -> i64 {
self.answer
}
pub fn components(&self) -> &Vec<i64> {
&self.components
}
fn compute_answer(&self, operators: &[bool]) -> i64 {
let mut accumulator = self.components[0];
for (i, op_bool) in operators.iter().enumerate() {
if *op_bool {
// Multiply
accumulator *= self.components[i + 1];
} else {
// Add
accumulator += self.components[i + 1];
}
}
accumulator
}
pub fn solvable(&self) -> bool {
let op_combinations = create_operator_set(self.components.len() - 1);
for combination in op_combinations {
if self.answer == self.compute_answer(&combination) {
return true;
}
}
false
}
}