make obtaining the register value *during* a cycle easier
This commit is contained in:
parent
71aa3605cd
commit
88e56549d7
|
@ -65,7 +65,7 @@ impl Processor {
|
|||
self.cycle_count = instruction.duration();
|
||||
}
|
||||
|
||||
pub fn step(&mut self) -> Result<i64, &'static str> {
|
||||
pub fn step(&mut self) -> i64 {
|
||||
match self.instruction {
|
||||
Instruction::Noop => self.cycle_count -= 1,
|
||||
Instruction::Addx { arg } => {
|
||||
|
@ -75,7 +75,7 @@ impl Processor {
|
|||
}
|
||||
}
|
||||
}
|
||||
Ok(self.x)
|
||||
self.x
|
||||
}
|
||||
|
||||
pub fn cycles(&mut self) -> Cycles {
|
||||
|
@ -83,12 +83,17 @@ impl Processor {
|
|||
}
|
||||
}
|
||||
|
||||
pub struct Cycle {
|
||||
pub x_during: i64,
|
||||
pub x_after: i64,
|
||||
}
|
||||
|
||||
pub struct Cycles<'a> {
|
||||
processor: &'a mut Processor,
|
||||
}
|
||||
|
||||
impl Iterator for Cycles<'_> {
|
||||
type Item = Result<i64, &'static str>;
|
||||
type Item = Result<Cycle, &'static str>;
|
||||
|
||||
fn next(&mut self) -> Option<Self::Item> {
|
||||
if self.processor.cycle_count == 0 {
|
||||
|
@ -102,6 +107,9 @@ impl Iterator for Cycles<'_> {
|
|||
Err(_) => assert!(false),
|
||||
}
|
||||
}
|
||||
Some(self.processor.step())
|
||||
Some(Ok(Cycle {
|
||||
x_during: self.processor.x,
|
||||
x_after: self.processor.step(),
|
||||
}))
|
||||
}
|
||||
}
|
||||
|
|
|
@ -22,9 +22,9 @@ use common::Processor;
|
|||
fn main() -> Result<(), &'static str> {
|
||||
let mut processor = Processor::new();
|
||||
let mut result = 0;
|
||||
for (count, register_x) in processor.cycles().enumerate() {
|
||||
if [20, 60, 100, 140, 180, 220].contains(&(count + 2)) {
|
||||
result += (count + 2) as i64 * register_x?;
|
||||
for (count, cycle) in processor.cycles().enumerate() {
|
||||
if [20, 60, 100, 140, 180, 220].contains(&(count + 1)) {
|
||||
result += (count + 1) as i64 * cycle?.x_during;
|
||||
}
|
||||
}
|
||||
println!("{result}");
|
||||
|
|
|
@ -21,10 +21,11 @@ use common::Processor;
|
|||
|
||||
fn main() -> Result<(), &'static str> {
|
||||
let mut processor = Processor::new();
|
||||
let mut line = String::from("#");
|
||||
for (count, register_x) in processor.cycles().enumerate() {
|
||||
let sprite = register_x? - 1..=register_x? + 1;
|
||||
match (count + 1) % 40 {
|
||||
let mut line = String::with_capacity(40);
|
||||
for (count, cycle) in processor.cycles().enumerate() {
|
||||
let x_during = cycle?.x_during;
|
||||
let sprite = x_during - 1..=x_during + 1;
|
||||
match count % 40 {
|
||||
pos if { sprite.contains(&(pos as i64)) } => line.push('#'),
|
||||
_ => line.push('.'),
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue