Last active
January 17, 2020 19:36
-
-
Save akrawchyk/1061d98fde8ecb7ec9fb329685681adf to your computer and use it in GitHub Desktop.
This file contains hidden or 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
/** | |
* @param {number[][]} board | |
* @return {void} Do not return anything, modify board in-place instead. | |
*/ | |
var gameOfLife = function(board) { | |
let neighbors = [0, 1, -1]; | |
let rows = board.length; | |
let cols = board[0].length; | |
let copyBoard = []; | |
copyBoard.length = rows; | |
for (let i = 0; i < rows; i++) { | |
for (let j = 0; j < cols; j++) { | |
if (!copyBoard[i]) { | |
copyBoard[i] = []; | |
copyBoard[i].length = cols; | |
} | |
copyBoard[i][j] = board[i][j]; | |
} | |
} | |
for (let row = 0; row < rows; row++) { | |
for (let col = 0; col < cols; col++) { | |
let liveNeighbors = 0; | |
for (let i = 0; i < 3; i++) { | |
for (let j = 0; j < 3; j++) { | |
if (!(neighbors[i] == 0 && neighbors[j] == 0)) { | |
let r = row + neighbors[i]; | |
let c = col + neighbors[j]; | |
if ((r < rows && r >= 0) && (c < cols && c >= 0) && (copyBoard[r][c] == 1)) { | |
liveNeighbors += 1; | |
} | |
} | |
} | |
} | |
if (copyBoard[row][col] == 1 && (liveNeighbors < 2 || liveNeighbors > 3)) { | |
board[row][col] = 0; | |
} | |
if (!copyBoard[row][col] && liveNeighbors == 3) { | |
board[row][col] = 1; | |
} | |
} | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment