2017-06-22 52 views
3

我正在使用其輸入是int二維數組的方法創建程序,該方法檢查數組是否爲Latin Squares用於檢查數組是否爲拉丁方的Java方法

例如拉丁方應該是這樣的:

1 2 3 
2 3 1 
3 1 2 

這是我到目前爲止的代碼:

public class LatinSquare { 

    public boolean isLatinSquare(int[][] a){ 

    int[] row= new int[a.length]; 
    int[] column = new int[a[0].length]; 

    for (int j = 0; j<column.length; j++){ 
     for (int i = 0; i<row.length;i++){ 
     row[i] = a[i][j]; 
     } 

     for (int i = 0; i<row.length -1; i++){ 
     for (int x= i+1; x<=row.length;x++){ 
      if (row[i]==row[x]) 
      return false; 
     } 
     } 
    } 
} 

的代碼沒有完全完成,但我只是想知道,如果有人能夠如果我做錯了什麼事,我會在錯誤的方向前回答一些問題。 我的問題:這是檢查數組看看他們是否會滿足拉丁廣場的最佳方法嗎?我的思考過程是,我從列'0'開始,然後遍歷行,將每個數字相互比較,確保它們不相等,並以這種方式遍歷每列。這是接近這個錯誤的方式嗎?

+0

你需要做的是在** ** TDD方式,寫簡單的測試最小允許廣場。 – fxrbfg

+0

據我所知,我試圖創建代碼,以便返回false,返回false,如果滿足所有參數,則返回true。 – Mike

回答

0

大量的嵌套循環會降低性能。這是一個更快的版本,但它使用了更多的內存。

它依賴於在範圍1N範圍內的平方的值,其中N是平方尺寸。

private static boolean isLatinSquare(int[][] square) { 
    boolean[][] foundInRow = new boolean[square.length][square.length]; 
    boolean[][] foundInCol = new boolean[square.length][square.length]; 
    for (int row = 0; row < square.length; row++) { 
     if (square[row].length != square.length) 
      return false; // Not a square 
     for (int col = 0; col < square.length; col++) { 
      int idx = square[row][col] - 1; 
      if (foundInRow[row][idx] || foundInCol[col][idx]) 
       return false; 
      foundInRow[row][idx] = foundInCol[col][idx] = true; 
     } 
    } 
    return true; 
} 

測試

System.out.println(isLatinSquare(new int[][] { {1, 2, 3}, 
               {2, 3, 1}, 
               {3, 1, 2} })); 
System.out.println(isLatinSquare(new int[][] { {1, 2, 3}, 
               {3, 1, 2}, 
               {2, 3, 1} })); 
System.out.println(isLatinSquare(new int[][] { {1, 3, 2}, 
               {2, 1, 3}, 
               {3, 2, 1} })); 
System.out.println(isLatinSquare(new int[][] { {1, 3, 2}, 
               {3, 2, 1}, 
               {2, 1, 3} })); 
System.out.println(isLatinSquare(new int[][] { {1, 3, 2}, 
               {3, 2, 1}, 
               {1, 3, 2} })); 
System.out.println(isLatinSquare(new int[][] { {1, 3, 1}, 
               {3, 2, 3}, 
               {2, 1, 2} })); 
System.out.println(isLatinSquare(new int[][] { {1, 2, 3}, 
               {2, 3}, 
               {3, 1, 2} })); 

輸出

true 
true 
true 
true 
false 
false 
false 
+0

謝謝你一定會幫助! – Mike

+0

我收到「System.out.println(isLatinSquare(newint [] [] ....」)代碼的錯誤代碼,它要求我重命名方法,並且在每個LatinSquare之後的括號和括號中有錯誤例如,「}))」。你知道這可能是爲什麼嗎? – Mike

+0

@Luke也許'new'和'int'之間缺少空格?它是'new int [] []',而不是'newint [] []'。此外,請確保將測試代碼放入方法中,例如'main()'方法。 – Andreas

相關問題