Skip to content

Instantly share code, notes, and snippets.

@viktorbezdek
Last active October 2, 2022 16:55
Show Gist options
  • Save viktorbezdek/5d6233f81a94387e3981bcf8079b56d1 to your computer and use it in GitHub Desktop.
Save viktorbezdek/5d6233f81a94387e3981bcf8079b56d1 to your computer and use it in GitHub Desktop.
Slightly Functional Game of Life
function boardGet(arr, i, j) {
if (i < 0 || j < 0 || i >= arr.length || j >= arr[i].length) {
return 0
}
return arr[i][j]
}
function countNeighbors(board, i, j) {
return (
boardGet(board, i - 1, j - 1) +
boardGet(board, i - 1, j) +
boardGet(board, i - 1, j + 1) +
boardGet(board, i, j - 1) +
boardGet(board, i, j + 1) +
boardGet(board, i + 1, j - 1) +
boardGet(board, i + 1, j) +
boardGet(board, i + 1, j + 1)
)
}
function isAlive(cell) {
return cell === 1
}
function shouldSurvive(cell, neighbors) {
if(isAlive(cell) && neighbors === 2 || neighbors === 3) return 1
if(!isAlive(cell) && neighbors === 3) return 1
return 0
}
function conwaysGameOfLife(board) {
return board.map((row, i) => row.map((cell, j) => shouldSurvive(cell, countNeighbors(board, i, j))))
}
var board = Array.from({ length: 50 }, () =>
Array.from({ length: 50 }, () => Math.round(Math.random()))
)
;(async () => {
let x = 1000
for (let i = 0; i < x; i++) {
console.clear()
board = conwaysGameOfLife(board)
console.log(board.map((i) => i.join(" ")).join("\n"))
await new Promise((resolve) => setTimeout(resolve, 50))
}
})()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment