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.

  • whoareuOP
    link
    fedilink
    arrow-up
    2
    ·
    4 days ago

    I’m going to assume that Python keeps multiple versions of the array in memory

    yeah you are right, I am passing the vector of numbers by reference, that’s why my solution doesn’t work.