53 lines
1.6 KiB
Java
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;
|
|
}
|
|
}
|