From 888928844893d318b4e5940fc9ba2dd6c45f8d1e Mon Sep 17 00:00:00 2001 From: mitchmindtree Date: Tue, 3 Mar 2020 11:47:32 +0100 Subject: [PATCH] Fix integer underflow panic in game of life wrap around example --- .../7_game_of_life_wrap_around.rs | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/examples/nature_of_code/chp_07_cellular_automata/7_game_of_life_wrap_around.rs b/examples/nature_of_code/chp_07_cellular_automata/7_game_of_life_wrap_around.rs index 9ffb7c941..2e87e9f40 100644 --- a/examples/nature_of_code/chp_07_cellular_automata/7_game_of_life_wrap_around.rs +++ b/examples/nature_of_code/chp_07_cellular_automata/7_game_of_life_wrap_around.rs @@ -60,10 +60,13 @@ impl Gol { for y in 0..self.rows { // Add up all the states in a 3x3 surrounding grid let mut neighbors = 0; - for i in 0..3 { - for j in 0..3 { - neighbors += self.board[(x + (i - 1) + self.columns) % self.columns] - [(y + (j - 1) + self.rows) % self.rows]; + for i in 0..3i32 { + for j in 0..3i32 { + let cols = self.columns as i32; + let rows = self.rows as i32; + let board_x = (x as i32 + (i - 1) + cols) % cols; + let board_y = (y as i32 + (j - 1) + rows) % rows; + neighbors += self.board[board_x as usize][board_y as usize]; } }