aoc/year2022/
day10.rs

1//! # Cathode-Ray Tube
2use crate::util::parse::*;
3
4/// Tokenizes the input treating both "noop" and "addx" as no-ops to obtain the correct
5/// instruction timing. Produces a `vec` of the absolute values of `x` from cycle 0 to 241.
6pub fn parse(input: &str) -> Vec<i32> {
7    let mut x = 1;
8    let mut xs = vec![1];
9
10    for token in input.split_ascii_whitespace() {
11        match token {
12            "noop" | "addx" => (),
13            delta => x += delta.signed::<i32>(),
14        }
15        xs.push(x);
16    }
17
18    xs
19}
20
21/// Converts between the 0-based indexing produced by the `parse` function and the 1-based indexing
22/// used by the problem statement.
23pub fn part1(input: &[i32]) -> i32 {
24    input.iter().enumerate().skip(19).step_by(40).map(|(i, x)| ((i + 1) as i32) * x).sum()
25}
26
27/// Returns pixels as a multi-line [`String`] so that the entire function can be integration tested.
28pub fn part2(input: &[i32]) -> String {
29    let to_char = |(i, c): (usize, &i32)| {
30        if ((i as i32) - c).abs() <= 1 { '#' } else { '.' }
31    };
32    let mut result = input
33        .chunks_exact(40)
34        .map(|row| row.iter().enumerate().map(to_char).collect())
35        .collect::<Vec<String>>()
36        .join("\n");
37    result.insert(0, '\n');
38    result
39}