import java.util.*;
public class Example {
public static void main(String[] args) {
int[][] solution = {
{9, 6, 3, 1, 7, 4, 2, 5, 8},
{1, 7, 8, 3, 2, 5, 6, 4, 9},
{2, 5, 4, 6, 8, 9, 7, 3, 1},
{8, 2, 1, 4, 3, 7, 5, 9, 6},
{4, 9, 6, 8, 5, 2, 3, 1, 7},
{7, 3, 5, 9, 6, 1, 8, 2, 4},
{5, 8, 9, 7, 1, 3, 4, 6, 2},
{3, 1, 7, 2, 4, 6, 9, 8, 5},
{6, 4, 2, 5, 9, 8, 1, 7, 3}
};
boolean ok = true;
int[] count = new int[9];
// row-wise loop
for (int i = 0; i < solution.length; i++) {
// -1 added for array index starting from 0, means 9 in above means count[8]
for (int j = 0; j < solution[0].length; j++) {
count[solution[i][j] - 1]++;
}
ok = checkIfOk(count);
reset(count);
}
// column-wise loop
for (int i = 0; i < solution.length; i++) {
// -1 added for array index starting from 0, means 9 in above means count[8]
for (int j = 0; j < solution[0].length; j++) {
count[solution[j][i] - 1]++;
}
ok = checkIfOk(count);
reset(count);
}
System.out.println(ok);
}
public static void reset(int[] arr) {
for (int i = 0; i < arr.length; i++) {
arr[i] = 0;
}
}
public static boolean checkIfOk(int[] arr) {
for (int i = 0; i < arr.length; i++) {
if (arr[i] > 1) {
return false;
}
}
return true;
}
}
So far, I’ve written to check row and column wise. I also have traced what to do for 3x3 grids.
top left subgrid
i=1-3
j=1-3
top middle subgrid
i=1-3
j=4-6
top right subgrid
i=1-3
j=7-9
middle left subgrid
i=4-6
j=1-3
middle middle subgrid
i=4-6
j=4-6
middle right subgrid
i=4-6
j=7-9
bottom left subgrid
i=7-9
j=1-3
bottom middle subgrid
i=7-9
j=4-6
bottom right subgrid
i=7-9
j=7-9
This is the pattern that I’ve caught. However, I am unable to exactly translate these stuffs to code.