Skip to content

Instantly share code, notes, and snippets.

@YonatanKra
Last active July 31, 2021 06:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save YonatanKra/47507ae0b4e16a918bc2fc1752d9a9e8 to your computer and use it in GitHub Desktop.
Save YonatanKra/47507ae0b4e16a918bc2fc1752d9a9e8 to your computer and use it in GitHub Desktop.
function cellularAutomaton(matrix) {
const tmpMatrix = copyMatrix(matrix);
tmpMatrix.forEach((row, rowIndex) => {
row.forEach((pixel, pixelIndex) => {
tmpMatrix[rowIndex][pixelIndex] = calculatePixelValueByNeighbors(rowIndex, pixelIndex, matrix);
});
});
return tmpMatrix;
}
function calculatePixelValueByNeighbors(rowIndex, pixelIndex, matrix) {
let sum = 0;
for (let y = -1; y < 2; y++) {
for (let x = -1; x < 2; x++) {
if (!matrix[rowIndex + y] || !matrix[rowIndex + y][pixelIndex + x]) {
sum -= 1;
} else {
sum += 1;
}
}
}
return sum > 0 ? WHITE : BLACK;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment