From 4c2ed31ae49d7d4f6f070b1d211e6286a9378bcd Mon Sep 17 00:00:00 2001 From: Ivan Dyachenko Date: Wed, 11 Dec 2024 16:33:30 +0300 Subject: [PATCH] Advent of Code 2024 [+] Day 7: Bridge Repair, Part 2 --- adventofcode/Cargo.toml | 1 + adventofcode/year2024/day07/part02.rs | 85 +++++++++++++++++++++++++++ 2 files changed, 86 insertions(+) create mode 100644 adventofcode/year2024/day07/part02.rs diff --git a/adventofcode/Cargo.toml b/adventofcode/Cargo.toml index 2ec3155..0ca5221 100644 --- a/adventofcode/Cargo.toml +++ b/adventofcode/Cargo.toml @@ -12,6 +12,7 @@ bin = [ { name = "2024-06-01", path = "year2024/day06/part01.rs" }, { name = "2024-06-02", path = "year2024/day06/part02.rs" }, { name = "2024-07-01", path = "year2024/day07/part01.rs" }, + { name = "2024-07-02", path = "year2024/day07/part02.rs" }, ] [package] diff --git a/adventofcode/year2024/day07/part02.rs b/adventofcode/year2024/day07/part02.rs new file mode 100644 index 0000000..e5f4986 --- /dev/null +++ b/adventofcode/year2024/day07/part02.rs @@ -0,0 +1,85 @@ +use core::panic; + +#[derive(Debug)] +pub struct Equation { + value: usize, + numbers: Vec, +} + +impl Equation { + pub fn parse(text: &str) -> Vec { + text.split("\n") + .filter(|l| !l.is_empty()) + .map(|l| { + let all: Vec = l + .split([':', ' ']) + .filter_map(|x| x.parse::().ok()) + .rev() + .collect(); + + match all.as_slice() { + [numbers @ .., value] => Equation { + value: *value, + numbers: numbers.to_vec(), + }, + _ => panic!(), + } + }) + .collect() + } + + pub fn is_possible(&self) -> bool { + evaluate(self.value, &self.numbers) + } +} + +fn evaluate(value: usize, numbers: &[usize]) -> bool { + match numbers { + [number] => value == *number, + [number, numbers @ ..] => { + let substraction = value as isize - *number as isize; + let substraction = if substraction < 0 { + false + } else { + evaluate(substraction as usize, numbers) + }; + + let division = value % *number; + let division = if division != 0 { + false + } else { + evaluate(value / *number, numbers) + }; + + let unconcat = { + let (value_str, number_str) = (value.to_string(), number.to_string()); + if value_str.len() > number_str.len() && value_str.ends_with(&number_str) { + let value = value_str[..value_str.len() - number_str.len()] + .parse::() + .unwrap(); + evaluate(value, numbers) + } else { + false + } + }; + + substraction || division || unconcat + } + _ => false, + } +} + +fn main() { + let text = std::fs::read_to_string("input.txt").unwrap(); + let equations = Equation::parse(&text); + + let answer = equations.iter().fold(0, |result, equation| { + if equation.is_possible() { + result + equation.value + } else { + result + } + }); + + println!("{:?}", answer); +}