diff options
Diffstat (limited to 'CLI/rust/src/game_of_life/simulation.rs')
| -rw-r--r-- | CLI/rust/src/game_of_life/simulation.rs | 48 |
1 files changed, 48 insertions, 0 deletions
diff --git a/CLI/rust/src/game_of_life/simulation.rs b/CLI/rust/src/game_of_life/simulation.rs new file mode 100644 index 0000000..bac44a0 --- /dev/null +++ b/CLI/rust/src/game_of_life/simulation.rs @@ -0,0 +1,48 @@ +/// Implement memeory safe indexing (circular indexing) +/// +/// When the index is out of bound (being negative or out of bound), the index +/// will try to fetch the item from the other end of the vector as if it's a +/// cylinder or circular array +fn circular_index(mut idx: isize, length: isize) -> usize { + while idx.is_negative() { + idx += length; + } + (idx % length) as usize +} + +#[cfg(test)] +mod circular_index { + use super::*; + + #[test] + fn negative_index() { + assert_eq!(circular_index(-1, 3), 2); + assert_eq!(circular_index(-2, 3), 1); + assert_eq!(circular_index(-3, 3), 0); + assert_eq!(circular_index(-4, 3), 2); + assert_eq!(circular_index(-5, 3), 1); + assert_eq!(circular_index(-6, 3), 0); + assert_eq!(circular_index(-7, 3), 2); + assert_eq!(circular_index(-8, 3), 1); + assert_eq!(circular_index(-9, 3), 0); + } + + #[test] + fn positve_index() { + assert_eq!(circular_index(0, 3), 0); + assert_eq!(circular_index(1, 3), 1); + assert_eq!(circular_index(2, 3), 2); + assert_eq!(circular_index(3, 3), 0); + assert_eq!(circular_index(4, 3), 1); + assert_eq!(circular_index(5, 3), 2); + assert_eq!(circular_index(6, 3), 0); + assert_eq!(circular_index(7, 3), 1); + assert_eq!(circular_index(8, 3), 2); + } +} + +/// Circular Plane used in Universe traversing +pub(crate) mod plane; + +/// Universe object used for simulation +pub(crate) mod universe; |
