Files
Sudoku/app/src/main/java/sudoku/solver/Solver.java
Janet-Doe 277eb76e60
All checks were successful
Linux arm64 / Build (push) Successful in 28s
feat coordinate
2025-01-21 16:59:50 +01:00

53 lines
1.6 KiB
Java

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<MutableCell> stack;
public Solver() {
}
public MultiDoku solve(MultiDoku doku, List<IConstraint> constraints) throws Exception {
if (!doku.isValid(constraints)) {
throw new Exception("Invalid doku");
}
List<MutableCell> allMutableCells = doku.getMutableCells();
List<MutableCell> 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;
}
}