Day 10, puzzle 1

This commit is contained in:
jazzpi 2022-12-15 15:44:37 +01:00
parent 71984d10d6
commit 05f3d9411a
3 changed files with 85 additions and 0 deletions

16
src/bin/d10p1.rs Normal file
View File

@ -0,0 +1,16 @@
use aoc22::{day10, util};
pub fn main() {
let instructions = day10::parse_instructions(&util::parse_input());
let mut cpu = day10::CPU::new(instructions);
let mut sum = 0;
for _ in 0..221 {
if (cpu.cycle - (20 - 1)) % 40 == 0 {
sum += cpu.signal_strength();
}
cpu.do_cycle().expect("No more instructions?");
}
println!("Sum of 20 + 40n cycles: {}", sum);
}

68
src/day10.rs Normal file
View File

@ -0,0 +1,68 @@
#[derive(Debug)]
pub enum Instruction {
Noop,
Addx(i32),
}
pub fn parse_instructions(input: &String) -> Vec<Instruction> {
let mut result = Vec::new();
for line in input.lines() {
if line == "noop" {
result.push(Instruction::Noop);
} else {
let (inst, v) = line.split_once(' ').unwrap();
assert_eq!(inst, "addx");
let v = v.parse().unwrap();
result.push(Instruction::Addx(v));
}
}
result
}
pub struct CPU {
pub x: i32,
pub cycle: isize,
instructions: Vec<Instruction>,
pc: usize,
inst_cycle: usize,
}
impl CPU {
pub fn new(instructions: Vec<Instruction>) -> CPU {
CPU {
x: 1,
cycle: 0,
instructions,
pc: 0,
inst_cycle: 0,
}
}
pub fn do_cycle(&mut self) -> Option<()> {
if let Some(inst) = self.instructions.get(self.pc) {
match inst {
Instruction::Noop => {
self.pc += 1;
}
Instruction::Addx(v) => {
self.inst_cycle += 1;
if self.inst_cycle == 2 {
self.pc += 1;
self.inst_cycle = 0;
self.x += v;
}
}
}
self.cycle += 1;
Some(())
} else {
None
}
}
pub fn signal_strength(&self) -> isize {
return (self.x as isize) * (self.cycle + 1);
}
}

View File

@ -1,4 +1,5 @@
pub mod day1;
pub mod day10;
pub mod day2;
pub mod day3;
pub mod day4;