summaryrefslogtreecommitdiffstats
path: root/CLI/rust/src/game_of_life/simulation.rs
blob: bac44a0dbc43995cd39b5510fc3a33350d8b799b (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
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;