Day 7 done

This commit is contained in:
Daniel Flanagan 2024-12-07 10:14:41 -06:00
parent 81337c405b
commit f954cdad24

View file

@ -5,25 +5,26 @@ pub use crate::prelude::*;
fn main() {
let input = day_input(7);
show_answers(sum_possibly_valid_tests(&input), 0);
show_answers(
sum_possibly_valid_tests(&input, &add_and_mul),
sum_possibly_valid_tests(&input, &add_and_mul_and_concat),
);
}
fn sum_possibly_valid_tests(input: &str) -> usize {
fn sum_possibly_valid_tests(input: &str, f: &dyn Fn(Vec<usize>, &usize) -> Vec<usize>) -> usize {
let mut sum = 0;
for l in input.lines() {
let (target, operands) = l.split_once(':').unwrap();
let target: usize = target.parse().unwrap();
println!("{target}");
let operands: Vec<usize> = operands
.trim()
.split(" ")
.map(|s| s.parse().unwrap())
.collect();
println!("{operands:?}");
if operands
.iter()
.skip(1)
.fold(vec![operands[0]], add_and_mul)
.fold(vec![operands[0]], f)
.iter()
.any(|n| *n == target)
{
@ -42,6 +43,16 @@ fn add_and_mul(lefts: Vec<usize>, right: &usize) -> Vec<usize> {
result
}
fn add_and_mul_and_concat(lefts: Vec<usize>, right: &usize) -> Vec<usize> {
let mut result = vec![];
for left in lefts {
result.push(left + right);
result.push(left * right);
result.push(format!("{}{}", left, right).parse().unwrap());
}
result
}
#[cfg(test)]
mod tests {
use super::*;
@ -58,9 +69,25 @@ mod tests {
161011: 16 10 13
192: 17 8 14
21037: 9 7 18 13
292: 11 6 16 20"
292: 11 6 16 20",
&add_and_mul
),
3749
)
);
assert_eq!(
sum_possibly_valid_tests(
"190: 10 19
3267: 81 40 27
83: 17 5
156: 15 6
7290: 6 8 6 15
161011: 16 10 13
192: 17 8 14
21037: 9 7 18 13
292: 11 6 16 20",
&add_and_mul_and_concat
),
11387
);
}
}