Reputation: 599
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?
Upvotes: 0
Views: 281
Reputation: 178263
The problem I see is with this line:
for (int column = 19; column < 3; column--)
This will be false
to start with and the block is never executed. You probably need
for (int column = 19; column >= 3; column--)
Use >=
so that the last valid value of column
is 3 (and so column - 3
evaluates to 0
and you reach the left side).
Upvotes: 3
Reputation: 70939
This cycle seems to be wrong: column = 19; column < 3; column--
you will never execute a single iteration. Maybe you meant column > 3
?
Upvotes: 2