Day 7 Part 1 implementation

This commit is contained in:
2025-06-16 10:54:22 -05:00
parent 775c4a50ca
commit 0b6ff3a4d0
2 changed files with 897 additions and 5 deletions

View File

@@ -43,12 +43,17 @@ enum Ops {
#[derive(Debug)]
struct Equation {
answer: i32,
components: Vec<i32>,
answer: i64,
components: Vec<i64>,
}
impl Equation {
/// Create a new Equation from a string like:
///
/// Answer: components
/// 190: 10 19
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));
@@ -62,21 +67,44 @@ impl Equation {
));
}
};
// Parse components
let components = split_equation[1]
.split_whitespace()
.map(|c| match c.parse::<i32>() {
.map(|c| match c.parse::<i64>() {
Ok(a) => Ok(a),
Err(_) => Err(format!(
"Error parsing component {} in equation: {}",
c, equation_str
)),
})
.collect::<Result<Vec<i32>, String>>()?;
.collect::<Result<Vec<i64>, String>>()?;
Ok(Equation { answer, 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
}
fn solvable(&self) -> bool {
let op_combination: HashSet<HashSet<i32>> = HashSet::new();
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
}
}
@@ -106,5 +134,19 @@ fn main() -> Result<(), Box<dyn Error>> {
let operator_set = create_operator_set(3);
println!("{:?}", operator_set);
let mut value_sum = 0;
println!("Is solvable?");
println!("------------");
for equation in equations {
let solvable = equation.solvable();
println!("{:?} => {}", equation, solvable);
if solvable {
value_sum += equation.answer;
}
}
println!("\n Total Calibration Result: {}", value_sum);
Ok(())
}