2017-06-22 59 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

相关问题