summaryrefslogtreecommitdiff
path: root/2022/rust/day10/src/main.rs
blob: 426be03200a579c83d5d6d7fefee16d16aeeadab (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
use {
    anyhow::{
        anyhow,
        Context,
        Result,
    },
    regex::Regex,
    std::{
        env::args,
        fs::File,
        io::{
            BufRead,
            BufReader,
        },
        path::Path,
    },
};

#[derive(Clone,Copy)]
enum Instruction {
    Addx(isize),
    Noop,
}

impl Instruction {
    fn cycles(&self) -> usize {
        match self {
            Instruction::Addx(_) => 2,
            Instruction::Noop    => 1,
        }
    }
}

#[derive(Clone)]
struct Program {
    inner: Vec<Instruction>,
}

impl Program {
    fn instruction(&self, cycle: usize) -> Option<Instruction> {
        let mut counter = 0;

        for instruction in self.inner.iter() {
            counter += instruction.cycles();
            match counter {
                c if c == cycle => return Some(*instruction),
                c if c > cycle => return None,
                _ => { },
            }
        }
        None
    }
}

struct Registers {
    x: isize,
}

impl Registers {
    fn new() -> Self {
        Self {
            x: 1,
        }
    }
}

struct Cpu {
    cycle: usize,
    program: Program,
    registers: Registers,
}

impl Cpu {
    fn new(program: Program) -> Self {
        let registers = Registers::new();

        Self {
            cycle: 0,
            program,
            registers,
        }
    }

    fn step(&mut self) {
        if let Some(instruction) = self.program.instruction(self.cycle) {
            match instruction {
                Instruction::Addx(argument) => self.registers.x += argument,
                Instruction::Noop => { },
            }
        }
        self.cycle += 1;
    }

    fn signal_strength(&self) -> isize {
        self.registers.x * self.cycle as isize
    }

    fn pixel(&self) -> String {
        if ((self.registers.x - 1)..=(self.registers.x + 1))
            .contains(&((self.cycle - 1) as isize % 40))
        {
            String::from("#")
        } else {
            String::from(".")
        }
    }
}

fn read_input<T: AsRef<Path>>(filename: T) -> Result<Program> {
    let reader = BufReader::new(File::open(filename)?);
    let re = Regex::new(r#"(?x)^
        (?P<instruction>(addx)|(noop))
        (
            \s
            (?P<argument>[0-9-]+)
        )?
    $"#)?;

    let instructions = reader.lines().map(
        |v| {
            let s = v?;
            let caps = re.captures(&s).ok_or_else(|| anyhow!("Could not parse: {s}"))?;
            let instruction = caps.name("instruction").unwrap_or_else(|| unreachable!()).as_str();
            let argument = caps.name("argument").map(|a| a.as_str()).unwrap_or_default();
            match instruction {
                "addx" => Ok(Instruction::Addx(argument.parse()?)),
                "noop" => Ok(Instruction::Noop),
                _ => unreachable!(),
            }
        }
    ).collect::<Result<Vec<_>>>()?;

    Ok(Program { inner: instructions })
}

fn part1(input: &Program) -> Result<isize> {
    let mut cpu = Cpu::new(input.clone());
    let mut sum = 0;

    for i in 0..=220 {
        if [20, 60, 100, 140, 180, 220].contains(&i) {
            sum += cpu.signal_strength();
        }
        cpu.step();
    }

    Ok(sum)
}

fn part2(input: &Program) -> Result<String> {
    let mut cpu = Cpu::new(input.clone());
    let mut output = String::default();

    for i in 0..240 {
        cpu.step();
        if i % 40 == 0 {
            output += "\n";
        }
        output += &cpu.pixel();
    }

    Ok(output)
}

fn main() -> Result<()> {
    let ( do_part_1, do_part_2 ) = aoc::do_parts();

    let filename = args().nth(1).ok_or_else(|| anyhow!("Missing input filename"))?;
    let input = read_input(filename).context("Could not read input")?;
    if do_part_1 {
        let solution = part1(&input).context("No solution for part 1")?;
        println!("Part1, solution found to be: {}", solution);
    }
    if do_part_2 {
        let solution = part2(&input).context("No solution for part 2")?;
        println!("Part2, solution found to be: {}", solution);
    }
    Ok(())
}