Day 7 part 1

This commit is contained in:
Daniel Flanagan 2024-12-07 10:10:48 -06:00
parent e5669fac3b
commit 81337c405b

66
2024/rust/src/day7.rs Normal file
View file

@ -0,0 +1,66 @@
mod prelude;
use std::slice::Windows;
pub use crate::prelude::*;
fn main() {
let input = day_input(7);
show_answers(sum_possibly_valid_tests(&input), 0);
}
fn sum_possibly_valid_tests(input: &str) -> 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)
.iter()
.any(|n| *n == target)
{
sum += target;
}
}
sum
}
fn add_and_mul(lefts: Vec<usize>, right: &usize) -> Vec<usize> {
let mut result = vec![];
for left in lefts {
result.push(left + right);
result.push(left * right);
}
result
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test() {
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"
),
3749
)
}
}