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.

  • CameronDevM
    link
    fedilink
    arrow-up
    1
    ·
    edit-2
    3 days ago

    Still reading, but this bit is a bit dopey:

    if calculate(answer, numbers) == true {
    		return true;
    	    } else {
    		return false;
    	    }
    

    I think your problem is you are passing around a reference to the 1 array, and the mutation of the array isnt reversed when you back out.

    So the array given to the multiply step and the add step end up different. Log them out and it should be clear