Compare commits

...

2 commits

Author SHA1 Message Date
Imbus
175545d3d5 Suitable exceptions for setBoard with corresponding tests 2023-12-10 15:04:04 +01:00
Imbus
f449d2343e Documentation now passes the gradle doctest 2023-12-10 15:03:10 +01:00
3 changed files with 26 additions and 12 deletions

View file

@ -12,7 +12,11 @@ public class Solver implements SudokuSolver {
/** {@inheritDoc} */
@Override
public void setBoard(int[][] board) {
public void setBoard(int[][] board) throws IllegalArgumentException, NullPointerException {
if (board == null)
throw new NullPointerException("Board cannot be null");
if (board.length != 9 || board[0].length != 9)
throw new IllegalArgumentException("Board must be 9x9");
this.board = board;
}
@ -28,7 +32,7 @@ public class Solver implements SudokuSolver {
board = new int[9][9];
}
/*{@inheritDoc} */
/* {@inheritDoc} */
@Override
public boolean solve() {
return solve(0, 0);
@ -107,7 +111,7 @@ public class Solver implements SudokuSolver {
}
// Recursively call randomizeBoard() until we get a solvable board
// This is expensive, and there should be some voodoo magic that computes this in n^2 time
// This is expensive, and there should be a better way to do this
if (!isSolvable()) {
randomizeBoard(difficulty);
}

View file

@ -1,5 +1,6 @@
package sudoku;
/** SudokuSolver is an interface for implementing Sudoku solvers */
public interface SudokuSolver {
/**
* Set sudoku board, numbers 1-9 are fixed values, 0 is unsolved.
@ -7,10 +8,12 @@ public interface SudokuSolver {
* @param board a board to copy values from
* @throws IllegalArgumentException if board is invalid, e.g. not 9x9
*/
void setBoard(int[][] board) throws IllegalArgumentException;
void setBoard(int[][] board) throws IllegalArgumentException, NullPointerException;
/**
* Get a copy of the sudoku board
*
* @return a <b>copy</b> of the sudoku board
*/
int[][] getBoard();
@ -24,9 +27,9 @@ public interface SudokuSolver {
/**
* Check if digit is legal on the current board
*
* @param row
* @param col
* @param nbr
* @param row row
* @param col column
* @param nbr number to check
* @return true if legal
*/
boolean isLegal(int row, int col, int nbr);
@ -34,8 +37,8 @@ public interface SudokuSolver {
/**
* Get number on board
*
* @param row
* @param col
* @param row row
* @param col column
* @return number on board
*/
int get(int row, int col);
@ -43,9 +46,9 @@ public interface SudokuSolver {
/**
* Set number on board, numbers 1-9 are fixed values, 0 is unsolved.
*
* @param row
* @param col
* @param nbr
* @param row row
* @param col column
* @param nbr number to set
*/
void set(int row, int col, int nbr);

View file

@ -106,4 +106,11 @@ class SolverTest {
solver.set(7, 1, 8);
assertFalse(solver.solve());
}
@Test
void setBoardInvalidInputThrowsTest() {
Solver solver = new Solver();
assertThrows(NullPointerException.class, () -> solver.setBoard(null));
assertThrows(IllegalArgumentException.class, () -> solver.setBoard(new int[8][8]));
}
}