patternjavaMinor
Java solution to check if a Sudoku solution is valid
Viewed 0 times
checkjavavalidsolutionsudoku
Problem
Here's my solution to checking if a Sudoku board is valid. The algorithm checks the following,
Invite comments.
- Rows add up to 45
- Columns add up to 45
- Rows have no duplicates
- Cols have no duplicates
- Every 3X3 sub-grid has no duplicate
Invite comments.
public class Checker {
private int size;
private int[][] board;
public Checker(int size){
this.size = size;
board = new int[size][size];
}
private boolean rowCheck(){
int sum = (size*(size+1))/2;
int count = 0;
for (int i = 0; i set = new HashSet<>();
for (int i = 0; i set = new HashSet<>();
for (int i = 0; i set = new HashSet<>();
for (int i = rowStart; i < rowFinish ; i++) {
for (int j =colStart ; j < colFinish; j++) {
set.add(board[i][j]);
}
if(set.size() != 9) return false;
}
return true;
}
public boolean isValid(){
return(rowCheck() && columnCheck() && checkRowDuplicates() && checkColumnDuplicates() && checkSubBoardDuplicates());
}
public void trace(){
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
System.out.print(board[i][j] + " ");
}
System.out.println();
}
}
}Solution
Your setting of
The point being that you should be setting the variable in advance of the loop, not resetting it afterwards (that being a pointless operation on the final iteration).
I would probably also move
count = 0 should be immediately before the appropriate for loop, not after it, and I would actually call that variable sum (renaming your sum to target) since it's not really a "count" at all, e.g:private boolean rowCheck(){
int target = size * (size + 1) / 2;
for (int i = 0; i <size; i++) {
int sum = 0; // declaration moved, too
for (int j = 0; j < size ; j++) {
sum += board[i][j];
}
if (sum != target) return false;
}
return true;
}The point being that you should be setting the variable in advance of the loop, not resetting it afterwards (that being a pointless operation on the final iteration).
I would probably also move
target into a class member, calculated in the constructor.Code Snippets
private boolean rowCheck(){
int target = size * (size + 1) / 2;
for (int i = 0; i <size; i++) {
int sum = 0; // declaration moved, too
for (int j = 0; j < size ; j++) {
sum += board[i][j];
}
if (sum != target) return false;
}
return true;
}Context
StackExchange Code Review Q#115912, answer score: 4
Revisions (0)
No revisions yet.