summaryrefslogtreecommitdiffstats
path: root/CLI/rust/src/game_of_life/simulation.rs
diff options
context:
space:
mode:
authora14m <[email protected]>2021-04-07 14:24:44 +0200
committera14m <[email protected]>2021-04-07 14:24:44 +0200
commitaa0c96b05c7012ac84a3787dcb2b661c7bf53029 (patch)
treed15247aa76f423f8d7220204344de9a53f17f0d7 /CLI/rust/src/game_of_life/simulation.rs
parentbd0ef4dcf5b46664c9e0b206f6acd8cf9b3532da (diff)
Refactor module structure to split universe/plane
The objects will grow bigger and might be hard for readability to keep them in 1 file hence the split
Diffstat (limited to 'CLI/rust/src/game_of_life/simulation.rs')
-rw-r--r--CLI/rust/src/game_of_life/simulation.rs48
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;