Last active
May 16, 2022 22:00
-
-
Save AnthonyMikh/a50a5a00c1844d9c5ad19c900b79d7f5 to your computer and use it in GitHub Desktop.
Neumann and Moore neighborhood calculation for rectangular grid
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#[derive(Clone, Copy)] | |
pub struct Bounds { | |
rows: usize, | |
cols: usize, | |
} | |
type Pos = (usize, usize); | |
impl Bounds { | |
pub fn around_neumann( | |
self, | |
buf: &mut [Pos; 4], | |
(row, col): Pos | |
) -> &[Pos] { | |
let mut i = 0; | |
let mut put = |r, c| { | |
buf[i] = (r, c); | |
i += 1; | |
}; | |
if let Some(row) = row.checked_sub(1) { | |
put(row, col); | |
} | |
if let Some(col) = col.checked_sub(1) { | |
put(row, col); | |
} | |
if col + 1 < self.cols { | |
put(row, col + 1); | |
} | |
if row + 1 < self.rows { | |
put(row + 1, col); | |
} | |
&buf[..i] | |
} | |
pub fn around_moore(self, buf: &mut [Pos; 8], (row, col): Pos) -> &[Pos] { | |
let mut i = 0; | |
let mut put = |r, c| { | |
buf[i] = (r, c); | |
i += 1; | |
}; | |
if let Some(row) = row.checked_sub(1) { | |
if let Some(col) = col.checked_sub(1) { | |
put(row, col); | |
} | |
put(row, col); | |
if col + 1 < self.cols { | |
put(row, col + 1); | |
} | |
} | |
if let Some(col) = col.checked_sub(1) { | |
put(row, col); | |
} | |
if col + 1 < self.cols { | |
put(row, col + 1); | |
} | |
if row + 1 < self.rows { | |
let row = row + 1; | |
if let Some(col) = col.checked_sub(1) { | |
put(row, col); | |
} | |
put(row, col); | |
if col + 1 < self.cols { | |
put(row, col + 1); | |
} | |
} | |
&buf[..i] | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment