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.

  • ImplyingImplications
    link
    fedilink
    arrow-up
    2
    ·
    5 days ago

    In case this helps too, here’s the Python version of your code (with print statements removed):

    def calculate(answer: int, numbers: list[int]) -> bool:
        if len(numbers) >= 2:
            tmp1 = numbers[0]
            tmp2 = numbers[1]
            numbers = numbers[2:]
    
            numbers.insert(0, tmp1*tmp2)
    
            if calculate(answer, numbers):
                return True
            else:
                numbers = numbers[1:]
                numbers.insert(0, tmp1+tmp2)
                return calculate(answer, numbers)
        else:
            return answer == numbers[0]
    
    • whoareuOP
      link
      fedilink
      arrow-up
      1
      ·
      4 days ago

      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.