Files
Sudoku/app/src/main/java/sudoku/solver/Solver.java
Persson-dev a1fd715aee
All checks were successful
Linux arm64 / Build (push) Successful in 24m1s
fix solver log display
2025-01-28 10:08:26 +01:00

119 lines
3.5 KiB
Java

package sudoku.solver;
import sudoku.io.SudokuPrinter;
import sudoku.structure.MultiDoku;
import sudoku.structure.Cell;
import sudoku.structure.Sudoku;
import java.util.List;
import java.util.Random;
import java.util.concurrent.CancellationException;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Solver {
private static final Logger logger = Logger.getLogger("SolverLogger");
/**
* Résout le multidoku passé en paramètre si c'est possible.
* En testant toutes les possibilités, de manière aléatoire, avec un algorithme
* de backtracking.
*
* @param doku Multidoku, à résoudre
* @param rand Random, pour tester aléatoirement les symboles
* @return boolean, true s'il est résolu ou false s'il ne l'est pas.
*/
public static boolean solveRandom(MultiDoku doku, Random rand) {
if (Thread.interrupted())
throw new CancellationException("User wants to stop the solver");
Sudoku sudoku = doku.getSubGrid(0);
logger.log(Level.INFO,
'\n' + SudokuPrinter.toStringRectangleSudoku(sudoku,
sudoku.getBlockWidth() == 0 ? sudoku.getSize() : sudoku.getBlockWidth(),
sudoku.getBlockWidth() == 0 ? sudoku.getSize() : sudoku.getSize() / sudoku.getBlockWidth()));
if (doku.isValid()) {
return true;
}
Cell cellToFill = doku.getFirstEmptyCell();
if (cellToFill == null) {
return false;
}
List<Integer> possibleSymbols = doku.getPossibleSymbolsOfCell(cellToFill);
while (!possibleSymbols.isEmpty()) {
int nextPossibleSymbolIndex = rand.nextInt(possibleSymbols.size());
int nextSymbol = possibleSymbols.get(nextPossibleSymbolIndex);
cellToFill.setSymbolIndex(nextSymbol);
if (Solver.solveRandom(doku, rand)) {
return true;
}
cellToFill.setSymbolIndex(Cell.NOSYMBOL);
possibleSymbols.remove(nextPossibleSymbolIndex);
}
return false;
}
public static int countSolution(MultiDoku doku) {
int result = 0;
if (doku.isValid()) {
return 1;
}
Cell cellToFill = doku.getFirstEmptyCell();
if (cellToFill == null) {
return 0;
}
List<Integer> possibleSymbols = doku.getPossibleSymbolsOfCell(cellToFill);
for (int symbol : possibleSymbols) {
cellToFill.setSymbolIndex(symbol);
if (Solver.solve(doku)) {
result++;
}
cellToFill.setSymbolIndex(Cell.NOSYMBOL);
}
return result;
}
public static boolean solve(MultiDoku doku) {
if (Thread.interrupted())
throw new CancellationException("User wants to stop the solver");
if (doku.isValid()) {
return true;
}
Cell cellToFill = doku.getFirstEmptyCell();
if (cellToFill == null) {
return false;
}
List<Integer> possibleSymbols = doku.getPossibleSymbolsOfCell(cellToFill);
if (possibleSymbols.isEmpty()) {
return false;
}
for (int symbol : possibleSymbols) {
cellToFill.setSymbolIndex(symbol);
if (Solver.solve(doku)) {
return true;
} else {
cellToFill.setSymbolIndex(Cell.NOSYMBOL);
}
}
return false;
}
}