New interface

This commit is contained in:
Imbus 2023-12-05 17:31:17 +01:00
parent ec37568e38
commit 0277a1f8b6
3 changed files with 61 additions and 29 deletions

View file

@ -24,7 +24,7 @@ public class Solver implements SudokuSolver {
/**
* Resets the board to all zeros
*/
public void reset() {
public void clear() {
board = new int[9][9];
}
@ -63,7 +63,7 @@ public class Solver implements SudokuSolver {
// Check for legal values in the current cell
for (int val = 1; val <= 9; ++val) {
if (legal(row, col, val)) {
if (isLegal(row, col, val)) {
board[row][col] = val;
// When we find a legal value, recursively call solve() on the next cell
if (solve(row + 1, col)) {
@ -80,25 +80,21 @@ public class Solver implements SudokuSolver {
* Randomizes the board. This guarantees a solvable board.
*/
public void randomizeBoard() {
this.reset();
this.clear();
for (int i = 0; i < 9; ++i) {
int row = (int) (Math.random() * 9);
int col = (int) (Math.random() * 9);
int val = (int) (Math.random() * 9) + 1;
if (legal(row, col, val)) {
if (isLegal(row, col, val)) {
board[row][col] = val;
}
}
}
/**
* Sets the value of the board at the given position
*
* @param row row to set
* @param col column to set
* @param val value to set
* {@inheritDoc}
*/
public void setPos(int row, int col, int val) {
public void set(int row, int col, int val) {
if (row < 9 && col < 9) {
board[row][col] = val;
}
@ -107,7 +103,17 @@ public class Solver implements SudokuSolver {
/**
* {@inheritDoc}
*/
public boolean legal(int row, int col, int val) {
public int get(int row, int col) {
if (row < 9 && col < 9) {
return board[row][col];
}
return 0;
}
/**
* {@inheritDoc}
*/
public boolean isLegal(int row, int col, int val) {
if (row < 0 || row >= 9 || col < 0 || col >= 9 || val < 1 || val > 9) {
return false;
}

View file

@ -3,11 +3,14 @@ package sudoku;
public interface SudokuSolver {
/**
* Set sudoku board, numbers 1-9 are fixed values, 0 is unsolved.
*
* @param board a board to copy values from
* @throws IllegalArgumentException if board is invalid, e.g. not 9x9
*/
void setBoard(int[][] board);
/**
* Get the sudoku board
* Get a copy of the sudoku board
*/
int[][] getBoard();
@ -26,5 +29,28 @@ public interface SudokuSolver {
* @param nbr
* @return true if legal
*/
boolean legal(int row, int col, int nbr);
}
boolean isLegal(int row, int col, int nbr);
/**
* Get number on board
*
* @param row
* @param col
* @return number on board
*/
int get(int row, int col);
/**
* Set number on board, numbers 1-9 are fixed values, 0 is unsolved.
*
* @param row
* @param col
* @param nbr
*/
void set(int row, int col, int nbr);
/**
* Clear the board
*/
void clear();
}