This program verifies if a matrix is a Sudoku or not. These conditions should be verified:
- There are no duplicates in a row, column, or square
- The sum of a row, column, or square should be equal to 45
public class SudokuChecker {
static int[][] invalidMatrix={
{5,5,5,5,5,5,5,5,5},
{1,2,5,5,5,5,5,5,5},
{5,5,5,5,5,5,5,5,5},
{5,5,5,5,5,5,5,5,5},
{5,5,5,5,5,5,5,5,5},
{5,5,5,5,5,5,5,5,5},
{5,5,5,5,5,5,5,5,5},
{5,5,5,5,5,5,5,5,5},
{5,5,5,5,5,5,5,5,5}
};
static int[][] validMatrix={
{5,3,4,6,7,8,9,1,2},
{6,7,2,1,9,5,3,4,8},
{1,9,8,3,4,2,5,6,7},
{8,5,9,7,6,1,4,2,3},
{4,2,6,8,5,3,7,9,1},
{7,1,3,9,2,4,8,5,6},
{9,6,1,5,3,7,2,8,4},
{2,8,7,4,1,9,6,3,5},
{3,4,5,2,8,6,1,7,9}
};
static int rSum = 0;
static int cSum = 0;
static int squareSum = 0;
static int[] rArray = new int[9];
static int[] cArray = new int[9];
static int[] squareArray = new int[9];
/*
* check of there is duplicates
*/
public static boolean checkDuplicate(int[] array){
Boolean duplicate = false;
Set<Integer> set= new HashSet<>();
for(int i : array){
if(set.contains(i)){
duplicate = true;
} else {
set.add(i);
}
}
return duplicate;
}
/*
* check if the sum of the element of a row are equals to 45
*/
public static boolean rowSum(int[][] matrix){
boolean correct = true;
for(int i =0; i < matrix.length; i++){
for(int j=0 ; j < matrix[i].length; j++){
rArray[j] = matrix[i][j];
rSum += rArray[j];
}
if(rSum != 45 || checkDuplicate(rArray) ){
correct = false;
break;
}
rSum = 0;
}
return correct;
}
/*
* check if the sum of the elements of a col are equals to 45
*/
public static boolean colSum(int[][] matrix){
boolean correct = true;
for(int j=0 ; j < matrix.length; j++){
for(int i=0 ; i < matrix.length ; i++){
cArray[i] = matrix[i][j];
cSum += cArray[i];
}
if(cSum != 45 || checkDuplicate(cArray)){
correct = false;
break;
}
cSum = 0;
}
return correct;
}
/*
* check if the sum of the elemnts of a square 3x3 are equals to 45
*/
public static boolean squareSum(int[][] matrix){
boolean correct = true;
for(int i=0; i < matrix.length ; i = i + 3){
for(int j=0; j < matrix.length ; j = j +3){
squareArray[0] = matrix[i][j];
squareArray[1] = matrix[i][j+1];
squareArray[2] = matrix[i][j+2];
squareArray[3] = matrix[i+1][j];
squareArray[4] = matrix[i+1][j+1];
squareArray[5] = matrix[i+1][j+2];
squareArray[6] = matrix[i+2][j];
squareArray[7] = matrix[i+2][j+1];
squareArray[8] = matrix[i+2][j+2];
squareSum = matrix[i][j] + matrix[i][j+1] + matrix[i][j+2]
+ matrix[i+1][j] + matrix[i+1][j+1] + matrix[i+1][j+2]
+ matrix[i+2][j] + matrix[i+2][j+1] + matrix[i+2][j+2] ;
if(squareSum != 45 || checkDuplicate(squareArray)){
correct = false;
break;
} else{
squareSum = 0;
}
}
}
return correct;
}
/*
* Test
*/
public static boolean test(int[][] matrix){
boolean correct = true;
if (!(rowSum(matrix) && colSum(matrix) && squareSum(matrix))){
correct = false;
}
return correct;
}
public static void main(String[] args) {
System.out.println(test(invalidMatrix) ? "Sudoku valide" : "Sudoku invalide");
}
}