day 7: part 1: rust

This commit is contained in:
Samuel Ortion 2024-12-10 16:15:21 +01:00
parent fd47622c68
commit ea51b3091d
Signed by: sortion
GPG Key ID: 9B02406F8C4FB765
2 changed files with 47 additions and 0 deletions

View File

@ -0,0 +1,6 @@
[package]
name = "part1"
version = "0.1.0"
edition = "2021"
[dependencies]

View File

@ -0,0 +1,41 @@
fn can_be_evaluated_to_aux(operands: &Vec<u64>, target: u64, current: u64, index: usize) -> bool {
if index == 0 {
return can_be_evaluated_to_aux(operands, target, operands[0], index + 1);
} else if index == operands.len() {
if current == target {
return true;
} else {
return false;
}
} else {
return can_be_evaluated_to_aux(operands, target, current * operands[index], index + 1) || can_be_evaluated_to_aux(operands, target, current + operands[index], index + 1);
}
}
fn can_be_evaluated_to(operands: &Vec<u64>, target: u64) -> bool {
return can_be_evaluated_to_aux(operands, target, 0, 0);
}
fn main() -> std::io::Result<()> {
let mut total: u64 = 0;
for line in std::io::stdin().lines() {
let line = line.unwrap();
if line != "".to_string() {
let mut parts = line.split(":");
let target = parts.next().unwrap();
let target = target.parse::<u64>().unwrap();
let operands: Vec<u64> = parts.next()
.unwrap()
.split(" ")
.skip(1)
.map(|e| e.parse::<u64>().unwrap())
.collect();
if can_be_evaluated_to(&operands, target) {
total += target;
}
}
}
println!("{}", total);
Ok(())
}