X-Git-Url: https://git.xandkar.net/?p=cellular-automata.git;a=blobdiff_plain;f=life%2F006%2Flife.ts;fp=life%2F006%2Flife.ts;h=695de908f5cd7043223984e4542b177c1d2eaf0c;hp=0204e5f0d3a72f858e2b79687f5392868a14b760;hb=c942e34c90c0508ab3ad124a53123daf99b9488d;hpb=e16b8b54be348430aef022ac39696df272100cd7 diff --git a/life/006/life.ts b/life/006/life.ts index 0204e5f..695de90 100644 --- a/life/006/life.ts +++ b/life/006/life.ts @@ -4,6 +4,63 @@ type States = Array; type Board = Array; +type GridLocation = {r: number, k: number}; + +class Grid { + private rows : number; + private columns : number; + private cells : Array>; + + constructor( + {rows, columns, init} : + { rows : number + , columns : number + , init : (location: GridLocation) => T + } + ) + { + this.rows = rows; + this.columns = columns; + let cells = []; + for (let r = 0; r < rows; r++) { + cells[r] = []; + for (let k = 0; k < columns; k++) { + cells[r][k] = init({r: r, k: k}) + }; + }; + this.cells = cells + }; + + moore_neighbors(origin : GridLocation) : Array { + let offsets = + [ {r: -1, k: -1}, {r: -1, k: 0}, {r: -1, k: 1} + , {r: 0, k: -1}, {r: 0, k: 1} + , {r: 1, k: -1}, {r: 1, k: 0}, {r: 1, k: 1} + ]; + let offset_to_location = + (offset) => {return {r: origin.r + offset.r, k: origin.k + offset.k}}; + let locations = offsets.map(offset_to_location); + let is_location_within_bounds = + ({r, k}) => r >= 0 && k >= 0 && r < this.rows && k < this.columns; + return locations.filter(is_location_within_bounds) + }; + + mapi(f : (location: GridLocation) => T) { + let cells = []; + for (let r = 0; r < this.rows; r++) { + cells[r] = []; + for (let k = 0; k < this.columns; k++) { + let location = {r: r, k: k}; + let neighbors = this.moore_neighbors(location); + cells[r][k] = f(location); + } + }; + let init = ({r, k}) => cells[r][k]; + let grid = new Grid({rows: this.rows, columns: this.columns, init: init}); + return grid + }; +}; + let state_of_integer = (i : number) : State => { switch (i) { case 0 : return "Dead" @@ -30,7 +87,7 @@ let board_new = ({rows, columns} : {rows: number, columns: number}) : Board => { return b }; -let board_neighbors = (b : Board, origin : {r: number, k: number}) : States => { +let board_neighbors = (b : Board, origin : GridLocation) : States => { let rows = b.length; let cols = b[0].length; let offsets =