Finish day 7 part 2

This commit is contained in:
2025-06-16 13:07:41 -05:00
parent 9f25697af4
commit 3815d496b9
3 changed files with 44 additions and 12 deletions

View File

@@ -48,10 +48,6 @@ impl Equation {
self.answer
}
pub fn components(&self) -> &Vec<i64> {
&self.components
}
fn compute_answer(&self, operators: &[Op]) -> i64 {
let mut accumulator = self.components[0];
@@ -59,6 +55,11 @@ impl Equation {
match op {
Op::Multiply => accumulator *= self.components[i + 1],
Op::Add => accumulator += self.components[i + 1],
Op::CONCAT => {
let accumulator_string = format!("{}", accumulator);
let component_string = format!("{}", self.components[i + 1]);
accumulator = (accumulator_string + &component_string).parse().unwrap();
}
}
}
@@ -78,4 +79,18 @@ impl Equation {
}
false
}
pub fn solvable_multiply_add_concat(&self) -> bool {
let op_combinations = create_permutations(
HashSet::from([Op::Add, Op::Multiply, Op::CONCAT]),
self.components.len() - 1,
);
for combination in op_combinations {
if self.answer == self.compute_answer(&combination) {
return true;
}
}
false
}
}

View File

@@ -1,13 +1,15 @@
use std::collections::HashMap;
use std::collections::HashSet;
use std::sync::{LazyLock, Mutex};
#[derive(Debug, Clone, Copy, Hash, PartialEq, Eq)]
pub enum Op {
Multiply,
Add,
CONCAT,
}
// use std::collections::HashMap;
// use std::sync::{LazyLock, Mutex};
// type OperatorCache = HashMap<usize, HashSet<Vec<Op>>>;
// static OPERATOR_SET_CACHE: LazyLock<Mutex<OperatorCache>> =

View File

@@ -33,19 +33,34 @@ fn main() -> Result<(), Box<dyn Error>> {
equations.push(Equation::new(&line)?)
}
let mut value_sum = 0;
let mut result_add_multiply = 0;
let mut result_add_multiply_concat = 0;
println!("Is solvable?");
println!("------------");
for equation in equations {
let solvable = equation.solvable_multiply_add();
println!("{:?} => {}", equation, solvable);
if solvable {
value_sum += equation.answer();
let solvable_add_multiply = equation.solvable_multiply_add();
let solvable_add_multiply_concat = equation.solvable_multiply_add_concat();
println!(
"{:?} => {} | {}",
equation, solvable_add_multiply, solvable_add_multiply_concat
);
if solvable_add_multiply {
result_add_multiply += equation.answer();
}
if solvable_add_multiply_concat {
result_add_multiply_concat += equation.answer();
}
}
println!("\n Total Calibration Result: {}", value_sum);
println!(
"\n Total Calibration Result (ADD|MULTIPLY): {}",
result_add_multiply
);
println!(
"\n Total Calibration Result (ADD|MULTIPLY|CONCAT): {}",
result_add_multiply_concat
);
Ok(())
}