From f3b7ead65bd6d498f28960051697496defbfa9db Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Fri, 7 Jul 2023 13:31:44 +0200 Subject: [PATCH] day(24): refactor the modular arithmetics Signed-off-by: Matej Focko --- src/bin/day24.rs | 58 ++++++++++++++++++++++++++++-------------------- 1 file changed, 34 insertions(+), 24 deletions(-) diff --git a/src/bin/day24.rs b/src/bin/day24.rs index aaa0ef9..261ed2c 100644 --- a/src/bin/day24.rs +++ b/src/bin/day24.rs @@ -39,31 +39,41 @@ impl Index for Basin { } // We need to account for the loops of the blizzards - let x_mod = self.cols - 2; - let y_mod = self.rows - 2; + let width = self.cols - 2; + let height = self.rows - 2; - let x_w = ((index.x() - 1 + x_mod - (index.z() % x_mod)) % x_mod + 1) as usize; - let x_e = ((index.x() - 1 + x_mod + (index.z() % x_mod)) % x_mod + 1) as usize; - let y_n = ((index.y() - 1 + y_mod - (index.z() % y_mod)) % y_mod + 1) as usize; - let y_s = ((index.y() - 1 + y_mod + (index.z() % y_mod)) % y_mod + 1) as usize; - - if self.map[index.y() as usize][x_w] == '>' { - return &self.map[index.y() as usize][x_w]; - } - - if self.map[index.y() as usize][x_e] == '<' { - return &self.map[index.y() as usize][x_e]; - } - - if self.map[y_n][index.x() as usize] == 'v' { - return &self.map[y_n][index.x() as usize]; - } - - if self.map[y_s][index.x() as usize] == '^' { - return &self.map[y_s][index.x() as usize]; - } - - &'.' + let blizzard_origin = |size, d, t, i| ((i - 1 + size + d * (t % size)) % size + 1) as usize; + [ + ( + index.y() as usize, + blizzard_origin(width, -1, index.z(), index.x()), + '>', + ), + ( + index.y() as usize, + blizzard_origin(width, 1, index.z(), index.x()), + '<', + ), + ( + blizzard_origin(height, -1, index.z(), index.y()), + index.x() as usize, + 'v', + ), + ( + blizzard_origin(height, 1, index.z(), index.y()), + index.x() as usize, + '^', + ), + ] + .iter() + .find_map(|&(y, x, direction)| { + if self.map[y][x] == direction { + Some(&self.map[y][x]) + } else { + None + } + }) + .unwrap_or(&'.') } }