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 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 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 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; } }