-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLatinSquares.java
84 lines (75 loc) · 2.93 KB
/
LatinSquares.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
import java.util.Scanner;
public class LatinSquares {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
//Get size of square from user
System.out.print("Enter number n: ");
int usernum = input.nextInt();
System.out.println("Enter " + usernum + " rows of letters separated by spaces: ");
String n = input.nextLine();
//Create memory for square
char[][] letterSquare = new char[usernum][usernum];
//Create loop to fill square
for(int i = 0; i < usernum; i++) {
String row = input.nextLine();
if(validLetters(row, usernum))
letterSquare[i] = getLetters(row, usernum);
//Error if letter input is out of range
else {
System.out.println("Wrong input: the letters must be from A to " + (char)(usernum + 64));
break;
}
//Print status of Latin square
if(i == usernum - 1)
System.out.println("The input array is " + (isLatinSquare(letterSquare) ? "" : "not " )
+ "a Latin square");
}
}
//Method to input letters
public static char[] getLetters(String row, int length) {
char[] letters = new char[length];
Scanner newchar = new Scanner(row);
for(int i = 0; i < length; i++) {
char c = newchar.next().charAt(0);
letters[i] = c;
}
return letters;
}
//Method to determine if square is Latin
public static boolean isLatinSquare(char[][] grid) {
for(int i = 0; i < grid.length; i++) {
if(repeatChars(grid[i]))
return false;
}
char[] col = new char[grid.length];
for(int i = 0; i < grid.length; i++) {
for(int j = 0; j < grid[i].length; j++) {
col[j] = grid[j][i];
}
if(repeatChars(col))
return false;
}
return true;
}
//Method to detect duplicate characters
public static boolean repeatChars(char[] c) {
for(int i = 0; i < c.length - 1; i++) {
for(int j = i + 1; j < c.length; j++) {
if(c[i] == c[j])
return true;
}
}
return false;
}
//Method to detect if letters are valid
public static boolean validLetters(String row, int usernum) {
Scanner newchar = new Scanner(row);
int letterLimit = 64 + usernum;
for(int i = 0; i < usernum; i++) {
int charInt = (int)(newchar.next().charAt(0));
if(charInt > letterLimit)
return false;
}
return true;
}
}