Advent of Rust // Day 10

After taking a day off, I’m a little behind. For some reason, I can’t wrap my head around part two of day 9, but fortunately, day 10 was easy again. Although it’s not very sophisticated to pre-compute all the cycles, it does make solving the puzzle easy.

fn input_to_cycle_values(input: &str) -> Vec<i32> {  
    let mut x = 1;  
    let mut cycle_values: Vec<i32> = Vec::new();  
  
    for line in input.lines() {  
        cycle_values.push(x);  
  
        if line.starts_with("addx") {  
            cycle_values.push(x);  
  
            x += line.split_once(" ").unwrap().1.parse::<i32>().unwrap();  
        }  
    }  
  
    cycle_values.push(x);  
  
    return cycle_values;  
}

fn part_one(input: &str) -> i32 {  
    let cycle_values = input_to_cycle_values(input);  
  
    return (19..cycle_values.len())  
        .step_by(40)  
        .map(|cycle| (cycle + 1) as i32 * cycle_values[cycle])  
        .sum();  
}

fn part_two(input: &str) -> String {  
    let mut screen = String::new();  
  
    for (cycle, x) in input_to_cycle_values(input).iter().take(240).enumerate() {  
        screen.push(if i32::abs(*x - (cycle % 40) as i32) > 1 { '.' } else { '#' });  
  
        if (cycle + 1) % 40 == 0 {  
            screen.push('\n');  
        }  
    }  
  
    return screen;  
}

The full source and solutions for the others puzzles of Advent of Code can be found in my GitHub repository.

See also in Advent of Rust

Comments

You can leave a comment by replying to this post on Mastodon.