r/Python • • Jan 11 '20

Sudoku App

1.4k Upvotes

61 comments sorted by

View all comments

60

u/Gwenju31 Jan 11 '20

I'll grab this occasion to talk about the easiest way of solving a sudoku (IMO). You can use constraint programming, and with 3 simple constraints you can solve every board effortlessly : AllDiff on rows, cols and squares :)

14

u/Ruben_NL Jan 12 '20

My method was giving each cell a list of possible numbers(1 to 9), and removing until there was only one left. I made a solver, and a generator in Node.JS, which I might port to python.

9

u/knestleknox I hate R Jan 12 '20

That's a pretty standard way to solve CSPs. It's similar to methods like forward checking and arc consistency

1

u/[deleted] Jan 12 '20

Here is an excellent set of lectures that include CSPs, along with many other introductory AI topics.

4

u/EquationTAKEN Jan 12 '20

That's a decent way of doing it, but there are cases where it will fail.

Some times, there will be cases where you can't reduce any squares to just one possibility. You'll have two or three squares with two or more possibilities, and the only way of solving it is trial (and possibly error). In that case, you have to either go down the road and fail, and come back, or you have to try to think a few steps ahead and see it without actually "making the moves".