2013-05-16 115 views
0

我試圖用計算20x20網格中四個相鄰數字(整數)中最大的產品。多維數組計算

這是我迄今爲止...

/** 
* 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; 
} 

我從我的項目的另一個複製這些代碼在(這正好是一個連接4個遊戲,使用8X8格)。顯然,我的Connect 4遊戲代碼無效。我的左對角線沒有通過測試用例,我很積極的解決了這個問題。

功能應該是相同的(只要計算產品),但我沒有找到正確的價值。

我的邏輯錯在哪裏?

回答

3

我看到的問題是這一行:

for (int column = 19; column < 3; column--) 

這將是false下手,並且永遠不會執行該塊。你可能需要

for (int column = 19; column >= 3; column--) 

使用>=,這樣的column最後有效值爲3(等column - 3計算爲0和到達左側)。

2

這個循環似乎是錯誤的:column = 19; column < 3; column--你永遠不會執行一次迭代。也許你的意思是column > 3

+0

嘿,簡單的錯誤。這解決了它。感謝您爲我抓到! – Jonathan

+0

您應該使用'column> = 3',這樣您還可以檢查列0-3的大小寫。如果您使用'column> 3',則最後一種情況將檢查第1-4列。 – rgettman

+0

我整合了這個修復,我只是忽略了條件dangit。多謝你們! – Jonathan