From 5e847bf86dd398bf5dd579428ddded4d9478291f Mon Sep 17 00:00:00 2001 From: elioat <{ID}+{username}@users.noreply.github.com> Date: Wed, 12 Jun 2024 11:56:42 -0400 Subject: * --- js/life.js | 53 ++++++++++++++++++++++++++++++----------------------- 1 file changed, 30 insertions(+), 23 deletions(-) diff --git a/js/life.js b/js/life.js index 443c796..7a5de14 100644 --- a/js/life.js +++ b/js/life.js @@ -2,41 +2,48 @@ const initialBoard = [ [0, 1, 0], [0, 0, 1], [1, 1, 1], - [0, 0, 0] -] + [0, 0, 0], +]; const getNextState = (board) => { - const rows = board.length - const cols = board[0].length + const rows = board.length; + const cols = board[0].length; const countLiveNeighbors = (board, x, y) => { - return [-1, 0, 1].reduce((acc, dx) => - acc + [-1, 0, 1].reduce((acc, dy) => - (dx === 0 && dy === 0) || x + dx < 0 || y + dy < 0 || x + dx >= rows || y + dy >= cols ? acc : acc + board[x + dx][y + dy] - , 0) - , 0) - } + return [-1, 0, 1].reduce( + (acc, dx) => + acc + [-1, 0, 1].reduce((acc, dy) => + (dx === 0 && dy === 0) || x + dx < 0 || y + dy < 0 || + x + dx >= rows || y + dy >= cols + ? acc + : acc + board[x + dx][y + dy], 0), + 0, + ); + }; return board.map((row, x) => row.map((cell, y) => { - const liveNeighbors = countLiveNeighbors(board, x, y) - return (cell === 1 && (liveNeighbors === 2 || liveNeighbors === 3)) || (cell === 0 && liveNeighbors === 3) ? 1 : 0 + const liveNeighbors = countLiveNeighbors(board, x, y); + return (cell === 1 && (liveNeighbors === 2 || liveNeighbors === 3)) || + (cell === 0 && liveNeighbors === 3) + ? 1 + : 0; }) - ) -} + ); +}; const printBoard = (board) => { - console.clear() - console.log(board.map(row => row.join(' ')).join('\n')) -} + console.clear(); + console.log(board.map((row) => row.join(" ")).join("\n")); +}; const runGame = async (initialBoard, generations) => { - let board = initialBoard + let board = initialBoard; for (let i = 0; i < generations; i++) { - printBoard(board) - board = getNextState(board) - await new Promise(resolve => setTimeout(resolve, 500)) // wait before printing the next step. + printBoard(board); + board = getNextState(board); + await new Promise((resolve) => setTimeout(resolve, 500)); // wait before printing the next step. } -} +}; -runGame(initialBoard, 5) +runGame(initialBoard, 100); -- cgit 1.4.1-2-gfad0