From 1b3394fd94c84c62a39b4521a88350391a447410 Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Sat, 10 Dec 2022 14:08:28 +0100 Subject: [PATCH] day(10): refactor a bit more Signed-off-by: Matej Focko --- src/bin/day10.rs | 39 ++++++++++++++++++--------------------- 1 file changed, 18 insertions(+), 21 deletions(-) diff --git a/src/bin/day10.rs b/src/bin/day10.rs index 8276f99..688cee5 100644 --- a/src/bin/day10.rs +++ b/src/bin/day10.rs @@ -1,9 +1,10 @@ -use std::{fmt::Display, str::FromStr}; +use std::{collections::HashMap, fmt::Display, str::FromStr}; use aoc_2022::*; use color_eyre::{eyre::eyre, Report}; use itertools::Itertools; +use lazy_static::lazy_static; type Input = Vec; type Output = Out; @@ -65,6 +66,10 @@ struct State { register: i32, } +lazy_static! { + static ref MAPPING: HashMap = HashMap::from([(false, ' '), (true, '█')]); +} + impl State { fn new() -> Self { Self { @@ -74,9 +79,7 @@ impl State { } fn check_signal_strength(&self, next_cycle: i32, total: &mut i32) { - *total += if let Some(cycle) = - (self.cycle..next_cycle).find(|&c| c >= 20 && (c + 20) % 40 == 0) - { + if let Some(cycle) = (self.cycle..next_cycle).find(|&c| c >= 20 && (c + 20) % 40 == 0) { // debug!( // "Adding {} x {} = {} to sum", // cycle, @@ -84,28 +87,22 @@ impl State { // cycle * self.register // ); - cycle * self.register - } else { - 0 - }; + *total += cycle * self.register; + } } fn draw_crt(&self, next_cycle: i32, screen: &mut Vec>) { // debug!("Checking: {:?} {:?}", i, (self.cycle..next.cycle)); - (self.cycle..next_cycle).for_each(|c| { - if screen.is_empty() || screen.last().unwrap().len() == 40 { - screen.push(vec![]); - } + (self.cycle..next_cycle) + .map(|c| (c - 1) % 40) + .for_each(|c| { + if screen.last().unwrap().len() == 40 { + screen.push(vec![]); + } - let idx = screen.len() - 1; - screen[idx].push( - if self.register - 1 <= (c - 1) % 40 && (c - 1) % 40 <= self.register + 1 { - '█' - } else { - ' ' - }, - ); - }); + let idx = screen.len() - 1; + screen[idx].push(MAPPING[&(self.register - 1..=self.register + 1).contains(&c)]); + }); } fn execute(&self, i: &Instruction, output: &mut Out) -> State {