fix(count, display): swapped x/y and i/j coordinates

- count: fixed (i, j) mixup and added >= 0 to both bounds check
- generation: swapped HEIGHT and WIDTH in loop order
This commit is contained in:
2025-05-03 07:28:48 +02:00
parent b053bbcbeb
commit 40e391b426

View File

@@ -16,6 +16,8 @@ fn display(grid: &[[bool; WIDTH]; HEIGHT], buffer: &mut String) {
} }
fn count(grid: &[[bool; WIDTH]; HEIGHT], x: usize, y: usize) -> u8 { fn count(grid: &[[bool; WIDTH]; HEIGHT], x: usize, y: usize) -> u8 {
// (i, j) coordinate
let near:[(isize, isize); 8] = [ let near:[(isize, isize); 8] = [
(-1, -1), (-1, 0), (-1, 1), (-1, -1), (-1, 0), (-1, 1),
(0, -1), (0, 1), (0, -1), (0, 1),
@@ -25,13 +27,13 @@ fn count(grid: &[[bool; WIDTH]; HEIGHT], x: usize, y: usize) -> u8 {
let mut count = 0; let mut count = 0;
for (i, j) in near { for (i, j) in near {
let nx: isize = x as isize + i; let nx: isize = x as isize + j;
let ny: isize = y as isize + j; let ny: isize = y as isize + i;
if (nx > 0 && (WIDTH as isize) > nx && if nx >= 0 && (WIDTH as isize) > nx &&
ny > 0 && (HEIGHT as isize) > ny) { ny >= 0 && (HEIGHT as isize) > ny {
if (grid[nx as usize][nx as usize]) { if grid[ny as usize][nx as usize] {
count += 1; count += 1;
} }
} }
@@ -43,10 +45,10 @@ fn count(grid: &[[bool; WIDTH]; HEIGHT], x: usize, y: usize) -> u8 {
fn generation(grid: &[[bool; WIDTH]; HEIGHT]) -> [[bool; WIDTH]; HEIGHT] { fn generation(grid: &[[bool; WIDTH]; HEIGHT]) -> [[bool; WIDTH]; HEIGHT] {
let mut new_grid = [[false; WIDTH]; HEIGHT]; let mut new_grid = [[false; WIDTH]; HEIGHT];
for x in 0..HEIGHT { for y in 0..HEIGHT {
for y in 0..WIDTH { for x in 0..WIDTH {
let count = count(grid, x, y); let count = count(grid, x, y);
new_grid[x][y] = match (grid[x][y], count) { new_grid[y][x] = match (grid[y][x], count) {
(true, 2) | (true, 3) => true, (true, 2) | (true, 3) => true,
(false, 3) => true, (false, 3) => true,
_ => false, _ => false,
@@ -61,8 +63,15 @@ fn main() {
let mut grid: [[bool; WIDTH]; HEIGHT] = [[false; WIDTH]; HEIGHT]; let mut grid: [[bool; WIDTH]; HEIGHT] = [[false; WIDTH]; HEIGHT];
let mut buffer: String = String::new(); let mut buffer: String = String::new();
// grid[14][13] = true;
// grid[15][14] = true;
// grid[13][15] = true;
// grid[14][15] = true;
// grid[15][15] = true;
loop { loop {
display(&grid, &mut buffer); display(&grid, &mut buffer);
grid = generation(&grid); grid = generation(&grid);
std::thread::sleep(std::time::Duration::from_millis(500));
} }
} }