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 mut result = String::new();
30
31    for row in input.chunks_exact(40) {
32        result.push('\n');
33        for (i, &c) in row.iter().enumerate() {
34            result.push(if ((i as i32) - c).abs() <= 1 { '#' } else { '.' });
35        }
36    }
37
38    result
39}