Hello,
I am trying to solve the day 7 using Rust and this is what I came up with so far:
use std::fs;
fn calculate(answer: &i32, numbers: &mut Vec<i32>) -> bool {
if numbers.len() >= 2 {
let tmp1 = numbers[0];
let tmp2 = numbers[1];
numbers.remove(0);
numbers.remove(0);
numbers.insert(0, tmp1 * tmp2);
if calculate(answer, numbers) == true {
return true;
} else {
numbers.remove(0);
numbers.insert(0, tmp1 + tmp2);
if calculate(answer, numbers) == true {
return true;
} else {
return false;
}
}
} else {
if *answer == numbers[0] {
println!("> {} true", numbers[0]);
return true;
} else {
println!("> {} false", numbers[0]);
return false;
}
}
}
fn main() {
let contents = fs::read_to_string("sample.txt")
.expect("Should have been able to read the file");
for line in contents.lines() {
let tmp = line.split(":").collect::<Vec<&str>>();
let answer = tmp[0].to_string().parse::<i32>().unwrap();
println!("{:?}", answer);
let numbers_str = tmp[1].split(" ");
let mut numbers: Vec<i32> = Vec::new();
for num in numbers_str {
if num.len() == 0 {
continue;
}
numbers.push(num.parse::<i32>().unwrap());
}
println!("{:?}", numbers);
if calculate(&answer, &mut numbers) == true {
println!("it's true");
}
}
}
I don’t know why the recursion is not working. any help would be appreciated.
Thanks I will try to run the python version and see if it works. I think the problem is that I am passing list of numbers by reference and in python it’s passed by value, this is the reason the python version works while mine doesn’t.