From: alex <> Date: Sat, 7 Dec 2024 08:32:24 +0000 (+0100) Subject: Day07 - part 2 X-Git-Url: https://aoc.elinar.fr/?a=commitdiff_plain;h=d678c6f2fb071300f69d31487b0a21207be462f0;p=aoc_2024 Day07 - part 2 --- diff --git a/src/day07.rs b/src/day07.rs index 1b1f41f..ae83c26 100644 --- a/src/day07.rs +++ b/src/day07.rs @@ -1,7 +1,28 @@ use std::error::Error; use std::path::Path; -fn possible_values(operands: &[u64]) -> Vec { +fn solve(input: &str, with_concat: bool) -> u64 { + input.lines() + .map(|l| { + let (tot, ops) = l.split_once(":").unwrap(); + let ops = ops.trim().split(" ") + .map(|v| v.parse::().unwrap()) + .collect::>(); + (tot.parse::().unwrap(), ops) + }) + .map(|(tot, ops)| { + let values = possible_values(&ops, with_concat); + if values.contains(&tot) { + tot + } + else { + 0 + } + }) + .sum() +} + +fn possible_values(operands: &[u64], with_concat: bool) -> Vec { let mut res: Vec = Vec::new(); for o in operands { if res.is_empty() { @@ -13,6 +34,10 @@ fn possible_values(operands: &[u64]) -> Vec { for t in tmp { res.push(t + o); res.push(t * o); + if with_concat { + let value = t.to_string() + &o.to_string(); + res.push(value.parse::().unwrap()); + } } } } @@ -22,32 +47,13 @@ fn possible_values(operands: &[u64]) -> Vec { fn run_part1(input: &str) -> Result> { println!("Running {} - part 1", get_day()); - let res = input.lines() - .map(|l| { - let (tot, ops) = l.split_once(":").unwrap(); - let ops = ops.trim().split(" ") - .map(|v| v.parse::().unwrap()) - .collect::>(); - (tot.parse::().unwrap(), ops) - }) - .map(|(tot, ops)| { - let values = possible_values(&ops); - if values.contains(&tot) { - tot - } - else { - 0 - } - }) - .sum(); - - Ok(res) + Ok(solve(input, false)) } fn run_part2(input: &str) -> Result> { println!("Running {} - part 2", get_day()); - Ok(0) + Ok(solve(input, true)) } pub fn run(input: &str) -> Result<(), Box> { @@ -87,6 +93,6 @@ mod tests { #[test] fn test_part2() { - assert_eq!(0, run_part2(TEXT_INPUT).unwrap()); + assert_eq!(11387, run_part2(TEXT_INPUT).unwrap()); } }