From 715def2e35e71f2ca3b7800ebffb11fe0ba0b2bf Mon Sep 17 00:00:00 2001 From: Joscha Date: Sat, 10 Dec 2022 15:23:14 +0100 Subject: [PATCH] [rs] Simplify 2022_10 --- rs/src/y2022/d10.rs | 53 +++++++++++---------------------------------- 1 file changed, 13 insertions(+), 40 deletions(-) diff --git a/rs/src/y2022/d10.rs b/rs/src/y2022/d10.rs index e915a91..bc963d1 100644 --- a/rs/src/y2022/d10.rs +++ b/rs/src/y2022/d10.rs @@ -1,39 +1,14 @@ -#[derive(Clone, Copy)] -struct State { - x: i32, -} - -struct Run { - history: Vec, - now: State, -} - -impl Run { - fn new() -> Self { - Self { - history: vec![], - now: State { x: 1 }, - } - } - - fn noop(&mut self) { - self.history.push(self.now); - } - - fn addx(&mut self, arg: i32) { - self.noop(); - self.noop(); - self.now.x += arg; - } -} - pub fn solve(input: String) { - let mut run = Run::new(); + let mut history = vec![]; + let mut reg_x = 1; + for line in input.lines() { if line == "noop" { - run.noop(); + history.push(reg_x); } else if let Some(arg) = line.strip_prefix("addx ") { - run.addx(arg.parse().unwrap()); + history.push(reg_x); + history.push(reg_x); + reg_x += arg.parse::().unwrap(); } else { panic!("Unknown instruction"); } @@ -41,18 +16,16 @@ pub fn solve(input: String) { let part1 = [20, 60, 100, 140, 180, 220] .into_iter() - .map(|i| run.history[i - 1].x * i as i32) + .map(|i| history[i - 1] * i as i32) .sum::(); println!("Part 1: {part1}"); println!("Part 2:"); - for chunk in run.history.chunks(40) { - for (x, state) in chunk.iter().enumerate() { - if (x as i32).abs_diff(state.x) <= 1 { - print!("#"); - } else { - print!("."); - } + for chunk in history.chunks(40) { + for (x, reg_x) in chunk.iter().enumerate() { + let visible = (x as i32).abs_diff(*reg_x) <= 1; + let pixel = if visible { '#' } else { '.' }; + print!("{pixel}"); } println!(); }