-
Notifications
You must be signed in to change notification settings - Fork 0
/
Validator.java
54 lines (46 loc) · 1.61 KB
/
Validator.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
import java.util.Set;
import java.util.HashSet;
public class Validator {
final public int[][] grid;
public int[][] subGrids = { { 0, 0 }, { 0, 3 }, { 0, 6 }, { 3, 0 }, { 3, 3 }, { 3, 6 }, { 6, 0 }, { 6, 3 },
{ 6, 6 }, };
private Set<Integer> numberSet = new HashSet<Integer>();
public Validator(int[][] grid) {
this.grid = grid;
}
/**
* We store all numbers in a set. There can be no repetions in a set, so if all
* numbers are in the row/column/subGrid the set should ideally have a size of
* 9. Thus, if the set's length is not 9, the given row/column/subGrid is not
* valid—a number is missing.
*/
public String isValidColumn(int col) {
numberSet.clear();
for (int i = 0; i < 9; i++) {
int num = grid[i][col];
numberSet.add(num);
}
return numberSet.size() == 9 ? "Valid" : "Invalid";
}
public String isValidRow(int row) {
numberSet.clear();
for (int i = 0; i < 9; i++) {
int num = grid[row][i];
numberSet.add(num);
}
return numberSet.size() == 9 ? "Valid" : "Invalid";
}
public String isValidSubGrid(int gridId) {
numberSet.clear();
int[] gridLocation = subGrids[gridId];
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
int row = gridLocation[0] + i;
int col = gridLocation[1] + j;
int num = grid[row][col];
numberSet.add(num);
}
}
return numberSet.size() == 9 ? "Valid" : "Invalid";
}
}