gridlife/
lib.rs

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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
#![warn(missing_docs)]
//! Game of Life
//!
//! Library to manage the grid state for Conways game of life.
//!
//! See: <https://en.wikipedia.org/wiki/Conway%27s_Game_of_Life>
use std::{
    fmt::{self, Debug, Display},
    ops::{Add, Index},
};

type Coord = i32;

const NORTH: Point = Point::new(0, -1);
const NORTH_EAST: Point = Point::new(1, -1);
const EAST: Point = Point::new(1, 0);
const SOUTH_EAST: Point = Point::new(1, 1);
const SOUTH: Point = Point::new(0, 1);
const SOUTH_WEST: Point = Point::new(-1, 1);
const WEST: Point = Point::new(-1, 0);
const NORTH_WEST: Point = Point::new(-1, -1);

const ORTHO_PLUS_DIR: [Point; 8] = [
    NORTH, NORTH_EAST, EAST, SOUTH_EAST, SOUTH, SOUTH_WEST, WEST, NORTH_WEST,
];

#[derive(Copy, Clone, Debug, Eq, PartialEq)]
struct Point {
    x: Coord,
    y: Coord,
}
impl AsRef<Point> for Point {
    fn as_ref(&self) -> &Self {
        self
    }
}

impl Add for Point {
    type Output = Self;

    #[inline]
    fn add(self, rhs: Self) -> Self::Output {
        Point::new(self.x + rhs.x, self.y + rhs.y)
    }
}

impl Point {
    #[inline]
    #[must_use]
    pub const fn new(x: Coord, y: Coord) -> Self {
        Point { x, y }
    }
}

#[derive(PartialEq, Clone, Copy, Debug)]
/// `CellState` models whether a cell has an alive or dead population
pub enum CellState {
    /// `Alive` with a `char` to be rendered
    Alive(char),
    /// `Dead` with a `char` to be rendered
    Dead(char),
}
impl Display for CellState {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            CellState::Dead(c) => {
                write!(f, "{c}")?;
            }
            CellState::Alive(c) => {
                write!(f, "{c}")?;
            }
        }
        Ok(())
    }
}

#[derive(PartialEq, Clone, Copy, Debug)]
struct NeighbourState {
    dead: i32,
    alive: i32,
}
#[derive(Debug)]
/// `Grid` holds the state for a Conways game of life
pub struct Grid<T> {
    /// The `width` of the grid to be created
    pub width: usize,
    /// The `height` of the grid to be created
    pub height: usize,
    /// The state of the grid in terms of what cells are alive and dead in automaton
    pub cells: Vec<T>,
    /// What character glyph should be used to display a dead population
    pub dead_glyph: char,
    /// What character glyph should be used to display an alive population
    pub alive_glyph: char,
}

impl<T> Grid<T> {
    fn contains(&self, p: &Point) -> bool {
        p.x >= 0 && (p.x as usize) < self.width && p.y >= 0 && (p.y as usize) < self.height
    }

    fn pos(&self, p: usize) -> Point {
        Point::new((p % self.width) as i32, (p / self.width) as i32)
    }
    fn idx(&self, p: &Point) -> usize {
        ((self.width as i32) * p.y + p.x) as usize
    }

    fn try_get<U: AsRef<Point>>(&self, p: U) -> Option<&T> {
        if self.contains(p.as_ref()) {
            Some(&self[*p.as_ref()])
        } else {
            None
        }
    }
}

impl<T> Index<Point> for Grid<T> {
    type Output = T;

    #[inline]
    fn index(&self, pos: Point) -> &Self::Output {
        &self.cells[self.idx(&pos)]
    }
}

impl Grid<CellState> {
    /// Create a new `Grid` of a given `width` and `height`.
    /// It will default to `X` for alive glyph and ` ` for dead glyph
    pub fn new_empty(width: usize, height: usize) -> Self {
        let size = width * height;
        let cells: Vec<CellState> = (0..size).map(|_| CellState::Dead(' ')).collect();
        Grid {
            width,
            height,
            cells,
            ..Default::default()
        }
    }

    fn generate_random_cells(size: usize, alive_glyph: char, dead_glyph: char) -> Vec<CellState> {
        (0..size)
            .map(|_| {
                if fastrand::bool() {
                    CellState::Alive(alive_glyph)
                } else {
                    CellState::Dead(dead_glyph)
                }
            })
            .collect()
    }
    /// Generate a new `Grid` of a given `width` and `height`
    /// It will be populated with a random distribution of Alive/Dead cells
    /// The default glyphs of `X` for alive and ` ` for dead.
    pub fn new_random(width: usize, height: usize) -> Self {
        let default = Self::default();
        let cells: Vec<CellState> =
            Self::generate_random_cells(width * height, default.alive_glyph, default.dead_glyph);
        Grid {
            width,
            height,
            cells,
            ..default
        }
    }

    /// Generate a new `Grid` of a given `width` and `height`
    /// It will be populated with a random distribution of Alive/Dead cells
    /// The glyphs can be overriddne with `alive_glyph` and `dead_glyph`
    pub fn new_random_custom_glyphs(
        width: usize,
        height: usize,
        alive_glyph: char,
        dead_glyph: char,
    ) -> Self {
        Grid {
            width,
            height,
            cells: Self::generate_random_cells(width * height, alive_glyph, dead_glyph),
            alive_glyph,
            dead_glyph,
        }
    }
    /// Re-generates the state of the `Grid` `cells` based on the rules of Conways game of life
    pub fn update_states(&mut self) -> u32 {
        let mut new_grid: Vec<CellState> = Vec::new();
        for (idx, &cell) in self.cells.iter().enumerate() {
            let state = self.get_neighbours_state(self.pos(idx));
            let cellstate = self.get_cell_state(&cell, state);
            new_grid.push(cellstate);
        }
        self.cells = new_grid;
        self.cells
            .iter()
            .filter(|&&c| c == CellState::Alive(self.alive_glyph))
            .count() as u32
    }
    /// Gets the new state of the current cell based on the following rules:
    /// - Any live cell with 0 or 1 live neighbors becomes dead, because of underpopulation
    /// - Any live cell with 2 or 3 live neighbors stays alive, because its neighborhood is just right
    /// - Any live cell with more than 3 live neighbors becomes dead, because of overpopulation
    /// - Any dead cell with exactly 3 live neighbors becomes alive, by reproduction
    fn get_cell_state(&self, cell: &CellState, state: NeighbourState) -> CellState {
        match (&cell, state.alive) {
            (CellState::Alive(_), 0..=1) => CellState::Dead(self.dead_glyph),
            (CellState::Alive(_), 2..=3) => CellState::Alive(self.alive_glyph),
            (CellState::Alive(_), 4..=8) => CellState::Dead(self.dead_glyph),
            (CellState::Dead(_), 3) => CellState::Alive(self.alive_glyph),
            (_, _) => *cell,
        }
    }
    fn get_neighbours_state(&self, point: Point) -> NeighbourState {
        let mut alive = 0;
        let mut dead = 0;
        for neighbour in self.get_neighbours(point).map(|p| self.try_get(p)) {
            match neighbour {
                Some(c) => match c {
                    CellState::Alive(_) => alive += 1,
                    CellState::Dead(_) => dead += 1,
                },
                None => {
                    continue;
                }
            }
        }
        NeighbourState { alive, dead }
    }

    fn get_neighbours(&self, point: Point) -> impl Iterator<Item = Point> + use<'_> {
        ORTHO_PLUS_DIR
            .into_iter()
            .map(move |d| point + d)
            .filter(|p| self.contains(p))
    }
}

impl Default for Grid<CellState> {
    fn default() -> Self {
        let size = 10 * 10;
        let cells: Vec<CellState> = (0..size).map(|_| CellState::Dead(' ')).collect();
        Grid {
            width: 10,
            height: 10,
            cells,
            alive_glyph: 'X',
            dead_glyph: ' ',
        }
    }
}

impl Display for Grid<CellState> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        for row in 0..self.height {
            for w in row * self.width..(row + 1) * self.width {
                write!(f, "{}", self.cells[w])?;
            }
            writeln!(f)?;
        }
        Ok(())
    }
}

#[allow(dead_code)]
impl<T: Debug> Grid<T> {
    fn print(&self) {
        println!("Grid {w}x{h}", w = &self.width, h = &self.height);
        for row in 0..self.height {
            println!(
                "r{row}: {:?}",
                &self.cells[row * self.width..(row + 1) * self.width]
            );
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_grid_try_get() {
        let g = Grid::new_empty(0, 0);
        assert!(g.try_get(Point { x: 10, y: 10 }) == None);
    }

    #[test]
    fn test_grid_new_random() {
        let rand_g = Grid::new_random(10, 10);
        assert_eq!(rand_g.cells.len(), 100);
    }

    #[test]
    fn test_get_neighbours_state() {
        let mut g = Grid::new_empty(3, 3);
        g.cells[1] = CellState::Alive(g.alive_glyph);
        // x 0 x
        // x x x
        // x x x
        let state = g.get_neighbours_state(Point { x: 0, y: 0 });
        assert_eq!(state.dead, 2);
        assert_eq!(state.alive, 1);
    }

    #[test]
    fn test_get_neighbours_state_unknown_point() {
        let g = Grid::new_empty(3, 3);
        let state = g.get_neighbours_state(Point { x: 5, y: 5 });
        assert_eq!(state.dead, 0);
        assert_eq!(state.alive, 0);
    }

    #[test]
    fn test_grid_display() {
        let mut g = Grid::new_empty(3, 3);
        g.cells[4] = CellState::Alive('X');
        let s = format!("{}", g);
        assert_eq!(s, "   \n X \n   \n".to_string());
    }

    #[test]
    fn test_grid_debug() {
        let mut g = Grid::new_empty(3, 3);
        g.cells[4] = CellState::Alive('X');
        let s = format!("{:?}", g);
        assert_eq!(s, "Grid { width: 3, height: 3, cells: [Dead(' '), Dead(' '), Dead(' '), Dead(' '), Alive('X'), Dead(' '), Dead(' '), Dead(' '), Dead(' ')], dead_glyph: ' ', alive_glyph: 'X' }".to_string());
    }

    #[test]
    fn test_update_state() {
        let mut g = Grid::new_random(10, 10);
        g.update_states();
    }

    #[test]
    fn test_get_cell_state() {
        let g = Grid::new_empty(3, 3);
        // Any live cell with 0 or 1 live neighbors becomes dead, because of underpopulation
        assert_eq!(
            g.get_cell_state(&CellState::Alive('X'), NeighbourState { alive: 1, dead: 0 }),
            CellState::Dead(' ')
        );
        //Any live cell with 2 or 3 live neighbors stays alive, because its neighborhood is just right
        assert_eq!(
            g.get_cell_state(&CellState::Alive('X'), NeighbourState { alive: 3, dead: 0 }),
            CellState::Alive('X')
        );
        // Any live cell with more than 3 live neighbors becomes dead, because of overpopulation
        assert_eq!(
            g.get_cell_state(&CellState::Alive('X'), NeighbourState { alive: 5, dead: 1 }),
            CellState::Dead(' ')
        );
        // Any dead cell with exactly 3 live neighbors becomes alive, by reproduction
        assert_eq!(
            g.get_cell_state(&CellState::Dead(' '), NeighbourState { alive: 3, dead: 0 }),
            CellState::Alive('X')
        );
    }

    #[test]
    fn test_new_random_custom_glyphs() {
        let g = Grid::new_random_custom_glyphs(3, 3, 'A', 'D');
        assert_eq!(g.cells.len(), 9);
        let unexpected_states: Vec<&CellState> = g
            .cells
            .iter()
            .filter(|c| {
                let state = c.to_string();
                state != "A" && state != "D"
            })
            .collect();
        assert_eq!(unexpected_states.len(), 0);
    }
}