From 2176502bd73598bbb9cf202eb653687463d61277 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lo=C3=AFc=20GUEZO?= Date: Thu, 1 May 2025 21:48:08 +0200 Subject: [PATCH] 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. --- src/main.rs | 29 ++++++++++++++++++++++++++++- 1 file changed, 28 insertions(+), 1 deletion(-) diff --git a/src/main.rs b/src/main.rs index 62deb32..61e2322 100644 --- a/src/main.rs +++ b/src/main.rs @@ -15,9 +15,36 @@ fn display(grid: &[[bool; WIDTH]; HEIGHT], buffer: &mut String) { 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() { let grid: [[bool; WIDTH]; HEIGHT] = [[false; WIDTH]; HEIGHT]; let mut buffer: String = String::new(); - display(&grid, &mut buffer); + loop { + display(&grid, &mut buffer); + } }