day 7: part 2: rust
This commit is contained in:
parent
ea51b3091d
commit
4619aaf4ed
|
@ -0,0 +1,6 @@
|
|||
[package]
|
||||
name = "part1"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
|
||||
[dependencies]
|
|
@ -0,0 +1,53 @@
|
|||
|
||||
fn concatenate_integers(a: u64, b: u64) -> u64 {
|
||||
let a_str = a.to_string();
|
||||
let b_str = b.to_string();
|
||||
let result_str = a_str + &b_str;
|
||||
let result: u64 = result_str.parse().unwrap();
|
||||
return result;
|
||||
}
|
||||
|
||||
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)
|
||||
|| can_be_evaluated_to_aux(operands, target, concatenate_integers(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(())
|
||||
}
|
Loading…
Reference in New Issue