summaryrefslogtreecommitdiff
path: root/2024_rust/src/lib.rs
diff options
context:
space:
mode:
authorGuillermo Ramos2024-12-20 10:06:49 +0100
committerGuillermo Ramos2024-12-20 10:06:49 +0100
commit59f7d2662a4d6c5faa2beda007de9ee5a9a108d6 (patch)
tree2a08f41ba00ece1a4d12593a10f0496b0e9b64aa /2024_rust/src/lib.rs
parent5d157540ef48e6b409e7ae6d7c07def820f72735 (diff)
downloadAoC-59f7d2662a4d6c5faa2beda007de9ee5a9a108d6.tar.gz
2024.16 (wrong p2)
Diffstat (limited to '2024_rust/src/lib.rs')
-rw-r--r--2024_rust/src/lib.rs57
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 {