diff options
Diffstat (limited to '2024_rust/src/lib.rs')
-rw-r--r-- | 2024_rust/src/lib.rs | 57 |
1 files changed, 57 insertions, 0 deletions
diff --git a/2024_rust/src/lib.rs b/2024_rust/src/lib.rs index f1a6a68..1bf0a7a 100644 --- a/2024_rust/src/lib.rs +++ b/2024_rust/src/lib.rs @@ -1,3 +1,51 @@ +pub mod direction { + #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] + pub enum Direction { + Up, + Right, + Down, + Left, + } + use Direction::*; + + impl Direction { + pub fn iter_all() -> impl Iterator<Item = Self> { + [Up, Right, Down, Left].into_iter() + } + + pub fn to_offset(&self) -> (isize, isize) { + match self { + Up => (-1, 0), + Right => (0, 1), + Down => (1, 0), + Left => (0, -1), + } + } + + pub fn rotate(&self) -> Self { + match self { + Up => Right, + Right => Down, + Down => Left, + Left => Up, + } + } + + pub fn around(&self) -> impl Iterator<Item = Self> + use<'_> { + Self::iter_all().filter(|&x| x != self.opposite()) + } + + pub fn opposite(&self) -> Self { + match self { + Up => Down, + Right => Left, + Down => Up, + Left => Right, + } + } + } +} + pub mod matrix { pub type Pos = (usize, usize); pub type PosDelta = (isize, isize); @@ -29,6 +77,15 @@ pub mod matrix { self.dots[x][y] = dot; } + pub fn in_bounds(&self, (x, y): PosDelta) -> Option<Pos> { + if x >= 0 && y >= 0 && x < self.limit.0 as isize && y < self.limit.1 as isize { + Some((x as usize, y as usize)) + } else { + None + } + } + + // todo use in_bounds pub fn pos_move(&self, (x, y): Pos, (dx, dy): PosDelta) -> Option<Pos> { let x2 = x as isize + dx; if x2 < 0 || x2 >= self.limit.0 as isize { |