Skip to content
Snippets Groups Projects

AoC 2023 day 9

  • Clone with SSH
  • Clone with HTTPS
  • Embed
  • Share
    The snippet can be accessed without any authentication.
    Authored by s91149
    main.rs 1.58 KiB
    fn main() {
        let input = std::fs::read_to_string("../inputs/input.txt").unwrap();
        let mut lines: Vec<Vec<i32>> = input
            .lines()
            .map(|line| {
                line.split_whitespace()
                    .map(|n| n.parse::<i32>().unwrap())
                    .collect()
            })
            .collect();
    
        println!("part 1: {}", solve(&lines));
        lines.iter_mut().for_each(|v| v.reverse());
        println!("part 2: {}", solve(&lines));
    }
    
    fn solve(lines: &[Vec<i32>]) -> i32 {
        let mut sum = 0;
        for numbers in lines.iter() {
            let mut all_steps: Vec<Vec<i32>> = Vec::new();
            let mut new_numbers = numbers.clone();
            all_steps.push(new_numbers.clone());
    
            while !new_numbers.iter().all(|&x| x == 0) {
                let mut current_numbers = Vec::with_capacity(new_numbers.len());
                for win in new_numbers.windows(2) {
                    let diff = win[1] - win[0];
                    current_numbers.push(diff);
                }
                new_numbers = current_numbers;
                all_steps.push(new_numbers.clone());
            }
            let mut prev_line: Option<Vec<i32>> = None;
    
            for step_line in all_steps.iter_mut().rev() {
                if let Some(prev_line) = prev_line {
                    let last = step_line.last().unwrap();
                    let prev_last = prev_line.last().unwrap();
                    step_line.push(last + prev_last);
                } else {
                    step_line.push(0);
                }
                prev_line = Some(step_line.clone());
            }
    
            let res = all_steps.first().unwrap().last().unwrap();
            sum += res;
        }
        sum
    }
    0% Loading or .
    You are about to add 0 people to the discussion. Proceed with caution.
    Finish editing this message first!
    Please register or to comment