about summary refs log tree commit diff stats
diff options
context:
space:
mode:
authorelioat <{ID}+{username}@users.noreply.github.com>2024-06-12 11:56:42 -0400
committerelioat <{ID}+{username}@users.noreply.github.com>2024-06-12 11:56:42 -0400
commit5e847bf86dd398bf5dd579428ddded4d9478291f (patch)
treec94a5919ba3dfeeb0534cd67e1c7f62964c89a3d
parent1bd51b5e9773d203c6be6020d5449973d6e25a3f (diff)
downloadtour-5e847bf86dd398bf5dd579428ddded4d9478291f.tar.gz
*
-rw-r--r--js/life.js53
1 files 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);