-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathvalidator.hpp
71 lines (66 loc) · 1.97 KB
/
validator.hpp
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
#pragma once
class Validator {
public:
static int gridIsValid(Grid &g) {
int sq_index [3] = {0,3,6};
for (int i = 0; i < 9; i++) {
// check for each row and each column
if (!checkRow(g,i) || !checkColumn(g,i)) return 0;
// check for each square
if (i%3==0) {
for (int col : sq_index) {
if (!checkSquare(g, i, col)) return 0;
}
}
}
return 1;
}
private:
static int checkRow(Grid &g, int row) {
int check [9] = { };
int sum = 0;
for (int i = 0; i < 9; i++) {
if (sum > 45) return 0;
int curr = g[row][i];
if (curr < 1 || curr > 9) return 0;
if (check[curr-1] == 1) return 0;
if (check[curr-1] == 0) {
check[curr-1]++;
sum += curr;
}
}
return sum == 45;
}
static int checkColumn(Grid &g, int col) {
int check [9] = { };
int sum = 0;
for (int i = 0; i < 9; i++) {
if (sum > 45) return 0;
int curr = g[i][col];
if (curr < 1 || curr > 9) return 0;
if (check[curr-1] == 1) return 0;
if (check[curr-1] == 0) {
check[curr-1]++;
sum += curr;
}
}
return sum == 45;
}
// row and col specifies the top left cell of the square
static int checkSquare(Grid &g, int row, int col) {
int check [9] = { };
int sum = 0;
for (int i = row; i < row + 3; i++) {
for (int j = col; j < col + 3; j++) {
int curr = g[i][j];
if (curr < 1 || curr > 9) return 0;
if (check[curr-1] == 1) return 0;
if (check[curr-1] == 0) {
check[curr-1]++;
sum += curr;
}
}
}
return sum == 45;
}
};