-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSudoku.java
More file actions
85 lines (71 loc) · 1.82 KB
/
Sudoku.java
File metadata and controls
85 lines (71 loc) · 1.82 KB
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
85
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class Sudoku {
int[][] sudokuBoard;
int n;
String filename;
public Sudoku(String filename) {
this.filename = filename;
}
public void buildSudoku(String nums) {
String[] numbers = nums.split(",");
for (int i = 0; i < numbers.length; i++) {
sudokuBoard[i/n][i%n] = Integer.parseInt(numbers[i]);
}
}
public void isValidSolution() {
int targetSum = (int) (Math.pow(2, n+1) - 2);
for (int i = 0; i < n; i++) {
int sumR = 0;
int sumC = 0;
for (int j = 0; j < n; j++) {
sumR+=Math.pow(2, sudokuBoard[i][j]);
sumC+=Math.pow(2, sudokuBoard[j][i]);
}
if (sumR != targetSum) {
System.out.println("False");
return;
}
if (sumC != targetSum) {
System.out.println("False");
return;
}
}
int blockSize = (int) Math.sqrt(n);
for (int i = 0; i < n; i+=blockSize) {
for (int j = 0; j < n; j+=blockSize) {
int sum = 0;
for (int x = i; x < i + blockSize; x++) {
for (int y = j; y < j + blockSize; y++) {
sum+=Math.pow(2, sudokuBoard[x][y]);
}
}
if (sum != targetSum) {
System.out.println("False");
return;
}
}
}
System.out.println("True");
}
public void verifySudoku() throws IOException {
BufferedReader br = new BufferedReader(new FileReader(filename));
String line;
while ((line = br.readLine()) != null) {
String[] params = line.split(";");
n = Integer.parseInt(params[0]);
sudokuBoard = new int[n][n];
buildSudoku(params[1]);
isValidSolution();
}
}
public static void main (String[] args) throws IOException {
if (args.length != 1) {
System.out.println("Unsupported number of parameters passed. Exiting.");
System.exit(1);
}
Sudoku s = new Sudoku(args[0]);
s.verifySudoku();
}
}