Day 10, puzzle 1
This commit is contained in:
parent
71984d10d6
commit
05f3d9411a
|
@ -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);
|
||||
}
|
|
@ -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);
|
||||
}
|
||||
}
|
|
@ -1,4 +1,5 @@
|
|||
pub mod day1;
|
||||
pub mod day10;
|
||||
pub mod day2;
|
||||
pub mod day3;
|
||||
pub mod day4;
|
||||
|
|
Loading…
Reference in New Issue