feat: add count function

It introduces a new `count` function that take:
- the grid arena
- X and Y as `isize`

It counts how many nearby cells are alive at a specified position and returns the total.
This commit is contained in:
2025-05-01 21:48:08 +02:00
parent f09f0efb7b
commit 2176502bd7

View File

@@ -15,9 +15,36 @@ fn display(grid: &[[bool; WIDTH]; HEIGHT], buffer: &mut String) {
println!("{}", buffer); println!("{}", buffer);
} }
fn count(grid: &[[bool; WIDTH]; HEIGHT], x: usize, y: usize) -> u8 {
let near:[(isize, isize); 8] = [
(-1, -1), (-1, 0), (-1, 1),
(0, -1), (0, 1),
( 1, -1), (1, 0), (1, 1)
];
let mut count = 0;
for (i, j) in near {
let nx: isize = x as isize + i;
let ny: isize = y as isize + j;
if (nx > 0 && (WIDTH as isize) > nx &&
ny > 0 && (HEIGHT as isize) > ny) {
if (grid[nx as usize][nx as usize]) {
count += 1;
}
}
}
return count;
}
fn main() { fn main() {
let grid: [[bool; WIDTH]; HEIGHT] = [[false; WIDTH]; HEIGHT]; let grid: [[bool; WIDTH]; HEIGHT] = [[false; WIDTH]; HEIGHT];
let mut buffer: String = String::new(); let mut buffer: String = String::new();
loop {
display(&grid, &mut buffer); display(&grid, &mut buffer);
} }
}