my teacher has given us a matrix and we are supposed to write a code that checks if it is a latin square or not. I have all of the pieces but I am having trouble putting them in order so they work. this is what she has given us to read the matrix she has created.
The text file is matrix.txt, here is what it contains.
3
1 2 3
3 1 2
2 3 1
As you can see this is a latin square, however, she said we can change the matrix to make sure it works with the other problems she gave us.
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();
}
}
}
This is the code I have currently. Where does it go?
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;
}
And I have no idea where this goes either...
if(LatinSquare(matrix)==false)
System.out.println("This is not a Latin Square");
else
System.out.println("This is a Latin Square");
Here is how I would do it
Multidim.java
matrix.txt
Note that your methods should follow Oracle's code conventions
That is why I changed
LatinSquare
tolatinSquare