Skip to content

Instantly share code, notes, and snippets.

@bltavares
Last active December 17, 2015 15:29
Show Gist options
  • Save bltavares/5632293 to your computer and use it in GitHub Desktop.
Save bltavares/5632293 to your computer and use it in GitHub Desktop.
function countNeighbours(grid, columnIndex, rowIndex){
var getCellValueForGrid = getCellValue.bind(this, grid);
var zipForPosition = zipWithSum.bind(this, [rowIndex, columnIndex]);
return [[-1,-1],[-1,0],[-1,1],
[-1, 0], [ 1,0],
[ 1,-1],[ 1,0],[ 1,1]].reduce(function(a,b) {
return a + getCellValueForGrid.apply(this, zipForPosition(b));
},0);
}
function zipWithSum(a,b) {
return a.map(function(e,i) { return e + b[i] });
}
function getCellValue(grid, rowIndex, columnIndex){
return +!!(grid[rowIndex] || [])[columnIndex];
}
countNeighbours = (grid, columnIndex, rowIndex) ->
getCellValueForGrid = getCellValue.bind(@, grid)
zipForPosition = zipWithSum.bind(@, [rowIndex, columnIndex])
[[-1,-1],[-1,0],[-1, 1],
[-1, 0], [ 1, 0],
[ 1,-1],[1, 0],[1, 1]].reduce ((a, b) ->
a + getCellValueForGrid.apply(@, zipForPosition(b))
), 0
zipWithSum = (a, b) ->
a.map (e, i) -> e + b[i]
getCellValue = (grid, rowIndex, columnIndex) ->
+!!(grid[rowIndex] or [])[columnIndex]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment