Skip to content

Instantly share code, notes, and snippets.

@stefanhuber
Created March 29, 2019 11:02
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 stefanhuber/866f83f4220a1c5b467d03d81cadff26 to your computer and use it in GitHub Desktop.
Save stefanhuber/866f83f4220a1c5b467d03d81cadff26 to your computer and use it in GitHub Desktop.
export class GameOfLife {
// number[][] == Array<Array<number>>
protected game:number[][];
constructor(game:Array<Array<number>>) {
this.game = game;
}
countLivingNeighbours(row:number, column:number) : number {
let count = 0;
for (let r = row - 1; r <= row + 1; r++) {
for (let c = column - 1; c <= column + 1; c++) {
if (r >= 0 && r < this.game.length &&
c >= 0 && c < this.game[0].length &&
(c != column || r != row))
count += this.game[r][c];
}
}
return count;
}
transform():Array<Array<number>> {
let nextGame:number[][] = [];
for (let row = 0; row < this.game.length; row++) {
nextGame[row] = [];
for (let column = 0; column < this.game[row].length; column++) {
let n = this.countLivingNeighbours(row, column);
nextGame[row][column] = this.nextState(this.game[row][column], n);
}
}
return nextGame;
}
nextState(state:number, neighbours:number) : number {
if (state == 0 && neighbours == 3) {
return 1;
} else if (state == 1 && neighbours >= 2 && neighbours <= 3) {
return 1;
} else {
return 0;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment