top | item 27889199

(no title)

wgetch | 4 years ago

Answer set programming is also well suited for combinatorial search problems such as this. The classic approach for ASP solvers is to reduce a logic program into an instance of the boolean SAT problem and feed that into a SAT solver. The language used in ASP is a variant of Prolog called AnsProlog. AnsProlog programs may have variables which are grounded before solving, and programs may produce any number of stable models (satisfiable solutions). Here is my own general Sudoku solver in AnsProlog:

    #const d=3.
    #const n=d*d.
    
    1 { s(X,Y,1..n) } 1 :- X=1..n, Y=1..n.
    % Achieved: A value is chosen for each cell

    X1=X2 :- s(X1,Y,N), s(X2,Y,N).
    Y1=Y2 :- s(X,Y1,N), s(X,Y2,N).
    % Achieved: No value is duplicated for any given row or column

    r(X,Y,Z) :- X=1..n, Y=1..n, Z=((X-1)/d)*d+((Y-1)/d)+1.
    (X1-X2)*(X1-X2)+(Y1-Y2)*(Y1-Y2)=0  :- s(X1,Y1,N), s(X2,Y2,N), r(X1,Y1,Z), r(X2,Y2,Z).
    % Achieved: No value is duplicated within a d*d region

    #show s/3.
The program above can be used to generate completed puzzles from scratch, or it can be combined with an input file containing an incomplete puzzle to generate any or all valid solutions. Due to the semantics of ASP, additional constraints can be appended to the program to support Sudoku variants without modifying the existing lines.

discuss

order

No comments yet.