我的老师给了我们一个矩阵,我们应该编写一个代码来检查它是否是拉丁方格。我有所有的东西,但我无法把它们整理好,这样它们才能工作。这就是她让我们阅读她创建的矩阵的内容。
文本文件是 matrix.txt,这是它包含的内容。
3
1 2 3
3 1 2
2 3 1
正如你所看到的,这是一个拉丁方格,然而,她说我们可以更改矩阵以确保它适用于她给我们提出的其他问题。
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Multidim {
public static void main(String args[]){
int matrix[][] = initMatrix();
//printData(matrix); //Uncomment to print array
/////YOUR MAIN CODE HERE/////
}
///PLACE YOUR METHODS HERE
public static int[][] initMatrix(){
int matrix[][];
Scanner filein = null;
try {
filein = new Scanner(new File("matrix.txt"));
int numRows = Integer.parseInt(filein.nextLine());
matrix = new int[numRows][];
parseData(matrix, filein);
filein.close();
return matrix;
} catch (FileNotFoundException e) {
System.out.println(e.getMessage());
if(filein != null)
filein.close();
return null;
}
}
public static void parseData(int matrix[][], Scanner in){
for(int r = 0; r < matrix.length; r++){
String splitLine[] = in.nextLine().split(" ");
matrix[r] = new int[splitLine.length];
for(int c = 0; c < matrix[r].length; c++){
matrix[r][c] = Integer.parseInt(splitLine[c]);
}
}
}
public static void printData(int matrix[][]){
for(int r = 0; r < matrix.length; r++){
for(int c = 0; c < matrix[r].length; c++){
System.out.print(matrix[r][c] + " ");
}
System.out.println();
}
}
}
这是我目前拥有的代码。它去哪儿了?
public static boolean LatinSquare(int[][]array) {
for(int i=0;i<array.length;i++) {
for(int j=0; j<array[i].length; j++) {
if(i!=j) {
return false;
}
}
}
return true;
}
public boolean DuplicatesInRows(int[][]array) {
for (int i=0; i<array.length; i++) {
for (int j=0;j<array[i].length; j++) {
int num=array[i][j];
for(int col =j+1; col<array.length; col++) {
if(num==array[i][col]) {
return true;
}
}
}
}
return false;
}
public boolean DuplicatesInCol(int[][]array) {
for(int i=0;i<array.length; i++) {
for(int j=0; j<array.length; j++) {
for(int k=1; k<array.length; k++) {
if (array[i][j+k]==array[i][j]) {
if (array[i][j]!=0) {
return true;
}
}
}
}
}
return false;
}
而且我也不知道这是怎么回事...
if(LatinSquare(matrix)==false)
System.out.println("This is not a Latin Square");
else
System.out.println("This is a Latin Square");