I'm trying to compute the largest product amongst four adjacent numbers (integers) in a 20x20 grid.
This is what I have so far...
/**
* The maxProduct method is used to compute the largest product across four
* consecutive integers (either horizontally, vertically, or diagonally).
*
* @param gridData - A 20x20 array containing the integer values.
* @return maxProduct - The largest product.
*/
private static int maxProduct(int[][] gridData)
{
int maxProduct = 0;
int currentProduct = 0;
// Compute the products across the columns.
for (int row = 0; row < 20; row++)
for (int column = 0; column < 17; column++)
{
currentProduct = gridData[row][column]
* gridData[row][column + 1] * gridData[row][column + 2]
* gridData[row][column + 3];
if (currentProduct > maxProduct)
{
maxProduct = currentProduct;
}
}
// Compute the products across the rows.
for (int column = 0; column < 20; column++)
for (int row = 0; row < 17; row++)
{
currentProduct = gridData[row][column]
* gridData[row + 1][column] * gridData[row + 2][column]
* gridData[row + 3][column];
if (currentProduct > maxProduct)
{
maxProduct = currentProduct;
}
}
// Compute the products across the right diagonals.
for (int column = 0; column < 17; column++)
for (int row = 0; row < 17; row++)
{
currentProduct = gridData[row][column]
* gridData[row + 1][column + 1]
* gridData[row + 2][column + 2]
* gridData[row + 3][column + 3];
if (currentProduct > maxProduct)
{
maxProduct = currentProduct;
}
}
// Compute the products across the left diagonals.
for (int column = 19; column < 3; column--)
for (int row = 0; row < 17; row++)
{
currentProduct = gridData[row][column]
* gridData[row + 1][column - 1]
* gridData[row + 2][column - 2]
* gridData[row + 3][column - 3];
if (currentProduct > maxProduct)
{
maxProduct = currentProduct;
}
}
return maxProduct;
}
I've copied this code over from another one of my projects (it happened to be a Connect 4 game that used an 8x8 grid). Apparently my code for the Connect 4 game didn't work. My left diagonals failed the test cases, and I'm positive I have fixed the issue within this method.
The functionality should be identical (as far as computing the products), yet I'm not finding the correct value.
Where is my logic wrong?