package sudoku.solver; import sudoku.MultiDoku; import sudoku.MutableCell; import sudoku.constraint.IConstraint; import java.util.ArrayList; import java.util.List; import java.util.Random; import java.util.Stack; public class Solver { Stack stack; public Solver() { } public MultiDoku solve(MultiDoku doku, List constraints) throws Exception { if (!doku.isValid(constraints)) { throw new Exception("Invalid doku"); } List allMutableCells = doku.getMutableCells(); List remainingCellsToCheck = new ArrayList<>(allMutableCells); Random rand = new Random(); while (!remainingCellsToCheck.isEmpty()) { int indexCurrentCell = rand.nextInt(remainingCellsToCheck.size()); MutableCell currentCell = remainingCellsToCheck.get(indexCurrentCell); if (currentCell.getPossibleSymbols().isEmpty()){ MutableCell modify = stack.pop(); modify.removeSymbolFromPossibilities(modify.clearCurrentSymbol()); } else { int symbol = currentCell.getPossibleSymbols().get(0); currentCell.setSymbolIndex(symbol); stack.push(currentCell); try { doku.updateSymbolsPossibilities(); } catch (Exception e) { //TODO rollback } //TODO check constraints integrity in sudoku } remainingCellsToCheck.remove(indexCurrentCell); } return doku; } }