Created
October 27, 2022 21:35
-
-
Save tyler274/ce98eb8e917c5b1306294cf885cf7526 to your computer and use it in GitHub Desktop.
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
/* | |
2x grid, nxm | |
cell alive or dead | |
at most 8 neighbors | |
living cell with exactly 2 or 3 living neighbors stays alive, otherwise dies | |
dead cell with exactly 3 living neighbors becomes alive. | |
input = [ | |
[True, False, True, False], | |
[False, False, False, True], | |
[True, True, True, False] | |
] | |
expected = [ | |
[False, False, False, False], | |
[True, False, False, True], | |
[False, True, True, False] | |
] | |
*/ | |
fn main() { | |
let mut grid: Vec<Vec<bool>> = vec![ | |
vec![true, false, true, false], | |
vec![false, false, false, true], | |
vec![true, true, true, false], | |
]; | |
let expected: Vec<Vec<bool>> = vec![ | |
vec![false, false, false, false], | |
vec![true, false, false, true], | |
vec![false, true, true, false], | |
]; | |
let ROW_MAX = grid.len() - 1; | |
let COL_MAX = grid.get(0).unwrap().len() - 1; | |
let mut new_grid = grid.clone(); | |
for (ridx, row) in grid.clone().iter_mut().enumerate() { | |
for (cidx, cell) in row.iter_mut().enumerate() { | |
let mut neighbors: Vec<bool> = Vec::new(); | |
if ridx != 0 { | |
if cidx == 0 { | |
// Left most column, no neighbors left | |
} else { | |
neighbors.push(grid[ridx - 1][cidx - 1]); | |
neighbors.push(grid[ridx][cidx - 1]); | |
if ridx != ROW_MAX { | |
neighbors.push(grid[ridx + 1][cidx - 1]); | |
} | |
} | |
neighbors.push(grid[ridx - 1][cidx]); | |
if ridx != ROW_MAX { | |
neighbors.push(grid[ridx + 1][cidx]); | |
} | |
if cidx != COL_MAX { | |
neighbors.push(grid[ridx - 1][cidx + 1]); | |
neighbors.push(grid[ridx][cidx + 1]); | |
if ridx != ROW_MAX { | |
neighbors.push(grid[ridx + 1][cidx + 1]); | |
} | |
} | |
} else { | |
if cidx == 0 { | |
// Left most column, no neighbors left | |
} else { | |
neighbors.push(grid[ridx][cidx - 1]); | |
if ridx != ROW_MAX { | |
neighbors.push(grid[ridx + 1][cidx - 1]); | |
} | |
} | |
if ridx != ROW_MAX { | |
neighbors.push(grid[ridx + 1][cidx]); | |
} | |
if cidx != COL_MAX { | |
neighbors.push(grid[ridx][cidx + 1]); | |
if ridx != ROW_MAX { | |
neighbors.push(grid[ridx + 1][cidx + 1]); | |
} | |
} | |
} | |
let n_alive = neighbors.iter().filter(|&&n| n == true).count(); | |
if !((n_alive == 2 || n_alive == 3) && *cell) { | |
new_grid[ridx][cidx] = false; | |
} | |
if n_alive == 3 && !*cell { | |
new_grid[ridx][cidx] = true; | |
} | |
} | |
} | |
println!("output {:?}", new_grid); | |
println!("expected {:?}", expected); | |
println!("Grids Match?: {}", new_grid == expected); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment