Created
September 2, 2021 08:13
-
-
Save lmammino/a548e003c4c26e043f46ab4eaadbe8e1 to your computer and use it in GitHub Desktop.
relative neighbour pixels in generic multidimensional spaces using const generics
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
fn neighbour_at<const D: usize>(i: u32) -> [i32; D] { | |
let mut el = [0_i32; D]; | |
let mut n = i; | |
for v in el.iter_mut().rev() { | |
*v = (n as i32 % 3) - 1; // -1 is needed because we offset the digits so that we are in range -1..1 | |
n /= 3; | |
} | |
el | |
} | |
#[cfg(test)] | |
mod ex17_tests { | |
use super::*; | |
#[test] | |
fn test_neighbour_at_d2() { | |
let neighbours: Vec<[i32; 2]> = (0..9).map(neighbour_at::<2>).collect(); | |
// D=2 | |
// 0 -> 0,0 -> -1,-1 | |
// 1 -> 0,1 -> -1,0 | |
// 2 -> 0,2 -> -1,1 | |
// 3 -> 1,0 -> 0,-1 | |
// 4 -> 1,1 -> 0,0 | |
// 5 -> 1,2 -> 0,1 | |
// 6 -> 2,0 -> 1,-1 | |
// 7 -> 2,1 -> 1,0 | |
// 8 -> 2,2 -> 1,1 | |
let expected = vec![ | |
[-1, -1], | |
[-1, 0], | |
[-1, 1], | |
[0, -1], | |
[0, 0], | |
[0, 1], | |
[1, -1], | |
[1, 0], | |
[1, 1], | |
]; | |
assert_eq!(neighbours, expected); | |
} | |
#[test] | |
fn test_neighbour_at_d3() { | |
let neighbours: Vec<[i32; 3]> = (0..27).map(neighbour_at::<3>).collect(); | |
// D=3 | |
// 0 -> 0,0,0 -> -1,-1,-1 | |
// 1 -> 0,0,1 -> -1,-1,0 | |
// 2 -> 0,0,2 -> -1,-1,1 | |
// 3 -> 0,1,0 -> -1,0,-1 | |
// 4 -> 0,1,1 -> -1,0,0 | |
// 5 -> 0,1,2 -> -1,0,1 | |
// 6 -> 0,2,0 -> -1,1,-1 | |
// 7 -> 0,2,1 -> -1,1,0 | |
// 8 -> 0,2,2 -> -1,1,1 | |
// 9 -> 1,0,0 -> 0,-1,-1 | |
// 10 -> 1,0,1 -> 0,-1,0 | |
// 11 -> 1,0,2 -> 0,-1,1 | |
// 12 -> 1,1,0 -> 0,0,-1 | |
// 13 -> 1,1,1 -> 0,0,0 | |
// 14 -> 1,1,2 -> 0,0,1 | |
// 15 -> 1,2,0 -> 0,1,-1 | |
// 16 -> 1,2,1 -> 0,1,0 | |
// 17 -> 1,2,2 -> 0,1,1 | |
// 18 -> 2,0,0 -> 1,-1,-1 | |
// 19 -> 2,0,1 -> 1,-1,0 | |
// 20 -> 2,0,2 -> 1,-1,1 | |
// 21 -> 2,1,0 -> 1,0,-1 | |
// 22 -> 2,1,1 -> 1,0,0 | |
// 23 -> 2,1,2 -> 1,0,1 | |
// 24 -> 2,2,0 -> 1,1,-1 | |
// 25 -> 2,2,1 -> 1,1,0 | |
// 26 -> 2,2,2 -> 1,1,1 | |
let expected = vec![ | |
[-1, -1, -1], | |
[-1, -1, 0], | |
[-1, -1, 1], | |
[-1, 0, -1], | |
[-1, 0, 0], | |
[-1, 0, 1], | |
[-1, 1, -1], | |
[-1, 1, 0], | |
[-1, 1, 1], | |
[0, -1, -1], | |
[0, -1, 0], | |
[0, -1, 1], | |
[0, 0, -1], | |
[0, 0, 0], | |
[0, 0, 1], | |
[0, 1, -1], | |
[0, 1, 0], | |
[0, 1, 1], | |
[1, -1, -1], | |
[1, -1, 0], | |
[1, -1, 1], | |
[1, 0, -1], | |
[1, 0, 0], | |
[1, 0, 1], | |
[1, 1, -1], | |
[1, 1, 0], | |
[1, 1, 1], | |
]; | |
assert_eq!(neighbours, expected); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment