Checking validation of entries in a Sudoku game written in Java
- by Mico0
I'm building a simple Sudoku game in Java which is based on a matrix (an array[9][9]) and I need to validate my board state according to these rules:
all rows have 1-9 digits
all columns have 1-9 digits.
each 3x3 grid has 1-9 digits.
This function should be efficient as possible for example if first case is not valid I believe there's no need to check other cases and so on (correct me if I'm wrong).
When I tried doing this I had a conflict. Should I do one large for loop and inside check columns and row (in two other loops) or should I do each test separately and verify every case by it's own?
(Please don't suggest too advanced solutions with other class/object helpers.)
This is what I thought about:
Main validating function (which I want pretty clean):
public boolean testBoard() {
boolean isBoardValid = false;
if (validRows())
{
if (validColumns())
{
if (validCube())
{
isBoardValid = true;
}
}
}
return isBoardValid;
}
Different methods to do the specific test such as:
private boolean validRows() {
int rowsDigitsCount = 0;
for (int num = 1; num <= 9; num++) {
boolean foundDigit = false;
for (int row = 0; (row < board.length) && (!foundDigit); row++) {
for (int col = 0; col < board[row].length; col++) {
if (board[row][col] == num) {
rowsDigitsCount++;
foundDigit = true;
break;
}
}
}
}
return rowsDigitsCount == 9 ? true : false;
}
I don't know if I should keep doing tests separately because it looks like I'm duplicating my code.