var grid = [],
nrows = 0,
ncols = 0,
theLargestProduct = 1;
for(var i = 0; i < nrows; i++) {
for(var j = 0; j < ncols; j++) {
var prod = Math.max.apply(null, [
get(i, j) * get(i, j+1) * get(i, j+2) * get(i, j+3), // right
get(i, j) * get(i+1, j) * get(i+2, j) * get(i+3, j), // down
get(i, j) * get(i+1, j+1) * get(i+2, j+2) * get(i+3, j+3), // diag right-down
get(i, j) * get(i+1, j-1) * get(i+2, j- 2) * get(i+3, j-3) // diag left-down
]);
if(prod > theLargestProduct) {
theLargestProduct = prod;
}
}
}
function get(i, j) {
if(i < 0 || i >= nrows || j < 0 || j >= ncols) {
// A convenience value when indexes are out of bounds.
return 0;
}
return grid[i * ncols + j];
}