Skip to content

Instantly share code, notes, and snippets.

@baptistemanson
Created March 25, 2022 11:55
Show Gist options
  • Save baptistemanson/4e409fa87063bd32ed5e19cc00c030ff to your computer and use it in GitHub Desktop.
Save baptistemanson/4e409fa87063bd32ed5e19cc00c030ff to your computer and use it in GitHub Desktop.
const DIM = 5;
/**
* -1-DIM -DIM +1-DIM
* -1 i +1
* -1+DIM +DIM +1+DIM
*/
const _compute = (m, out) => {
for (let x = 1; x < DIM; x++) {
for (let y = 1; y < DIM; y++) {
const i = x + y * DIM;
const nbAlive =
m[i - 1] +
m[i + 1] +
m[i + DIM] +
m[i + DIM - 1] +
m[i + DIM + 1] +
m[i - DIM] +
m[i - DIM - 1] +
m[i - DIM + 1];
if (m[i] && (nbAlive === 2 || nbAlive === 3)) out[i] = 1;
else if (m[i] && nbAlive === 3) out[i] = 1;
else out[i] = 0;
}
}
return out;
};
const nextGen = () => {
m1 = _compute(m1, m2);
};
const createMatrix = () => new Uint8Array((DIM + 2) * (DIM + 2)); // paddedd array
// TEST CASES
let m1 = createMatrix();
// fixtures
m1[1 + DIM] = 1;
m1[3 + DIM] = 1;
m1[4 + DIM] = 1;
m1[1 + DIM * 2] = 1;
m1[2 + DIM * 2] = 1;
m1[DIM * DIM] = 1;
let m2 = createMatrix();
const display = () => {
for (let x = 1; x < DIM; x++) {
out = "";
for (let y = 1; y < DIM; y++) {
out += m1[x + y * DIM];
}
console.log(out);
}
console.log("");
};
display(m1);
nextGen();
display(m1);
nextGen();
display(m1);
nextGen();
display(m1);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment