metal-pony / bucket-js

A bucket for my js utilities
MIT License
0 stars 0 forks source link

Optimize sudoku.isSolved #20

Open metal-pony opened 5 months ago

metal-pony commented 5 months ago

Currently, isSolved calls isFull, then isValid for each row, column, and region.

Further ideas to think about:

metal-pony commented 2 months ago

This will encompass several optimizations via caching certain data points used throughout the code. Each time a cell is updated, we will:

Currently, the solver (searchForSolutions3) is creating many extra Sudoku instances to populate node.nexts. Change node data to track (1) the index of the cell being tried and (2) the remaining candidates (as an encoded 9-bit int, same as board values in state). That should eliminate some garbage and should be faster - benchmark it to see. Then, each time the search backtracks, if remaining candidates > 0, replace the cell digit with a new candidate, remove the candidate from node.nexts, and continue the search. While remaining candidates is 0, just keep backtracking. Also note that because reduce() is called between guesses and fills in empty spaces, we'll need a way to remove the reduced cells when backtracking. Maybe a 3rd node data point board mask could be tracked before guessing, and each backtrack resets cells to empty via the mask.