From 05f3d9411ab3318329a6e298796ce00f2ed97e42 Mon Sep 17 00:00:00 2001 From: jazzpi Date: Thu, 15 Dec 2022 15:44:37 +0100 Subject: [PATCH] Day 10, puzzle 1 --- src/bin/d10p1.rs | 16 ++++++++++++ src/day10.rs | 68 ++++++++++++++++++++++++++++++++++++++++++++++++ src/lib.rs | 1 + 3 files changed, 85 insertions(+) create mode 100644 src/bin/d10p1.rs create mode 100644 src/day10.rs diff --git a/src/bin/d10p1.rs b/src/bin/d10p1.rs new file mode 100644 index 0000000..ee6b7b4 --- /dev/null +++ b/src/bin/d10p1.rs @@ -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); +} diff --git a/src/day10.rs b/src/day10.rs new file mode 100644 index 0000000..dbe0b52 --- /dev/null +++ b/src/day10.rs @@ -0,0 +1,68 @@ +#[derive(Debug)] +pub enum Instruction { + Noop, + Addx(i32), +} + +pub fn parse_instructions(input: &String) -> Vec { + 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, + pc: usize, + inst_cycle: usize, +} + +impl CPU { + pub fn new(instructions: Vec) -> 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); + } +} diff --git a/src/lib.rs b/src/lib.rs index 73bc0a8..40ba72e 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,4 +1,5 @@ pub mod day1; +pub mod day10; pub mod day2; pub mod day3; pub mod day4;