Sudoku: Difference between revisions

2,086 bytes added ,  14 years ago
Added Oz solution.
(Undo revision 69015 by Zinabo (Talk) — Reverting replacement of Common Lisp example and header with code fragment)
(Added Oz solution.)
Line 501:
let () = C.coloring g 9; display ()</lang>
 
=={{header|Oz}}==
 
<lang oz>declare
%% A board is a list of nine rows.
Board1 = [[4 _ _ _ _ _ _ 6 _]
[5 _ _ _ 8 _ 9 _ _]
[3 _ _ _ _ 1 _ _ _]
[_ 2 _ 7 _ _ _ _ 1]
[_ 9 _ _ _ _ _ 4 _]
[8 _ _ _ _ 3 _ 5 _]
[_ _ _ 2 _ _ _ _ 7]
[_ _ 6 _ 5 _ _ _ 8]
[_ 1 _ _ _ _ _ _ 6]]
 
%% Helper function: map the range 1..9 to something.
fun {MapRange F}
{Map [1 2 3 4 5 6 7 8 9] F}
end
 
%% Returns the board as a list of rows.
fun {Rows Board}
Board %% This is already the representation we have chosen.
end
 
%% Returns the board as a list of columns.
fun {Columns Board}
{MapRange fun {$ I} {Column Board I} end}
end
 
%% Returns the Board as a list of boxes (sub-grids).
fun {Boxes Board}
{MapRange fun {$ I} {Box Board I} end}
end
 
%%
fun {Column Board Index}
{Map Board
fun {$ Row}
{Nth Row Index}
end
}
end
 
%%
fun {Box Board Index1}
Index = Index1-1
Fields = {Flatten Board}
Start = (Index div 3) * 27 + (Index mod 3)*3
in
{Flatten
for I in 0..2 collect:C do
{C {List.take {List.drop Fields Start+I*9} 3}}
end
}
end
 
%% Clone the unbound variables in Board.
%% (Because we cannot constrain free toplevel variables.)
fun {Fresh Board}
{Map Board
fun {$ Line}
{Map Line fun {$ F} if {IsDet F} then F else _ end end}
end
}
end
 
%% Create a solver script given an initial board.
fun {GetScript InitBoard}
proc {$ Board}
%% Every row is a list of nine finite domain vars with the domain 1..9.
Board = {MapRange fun {$ _} {FD.list 9 1#9} end}
%% Post initial configuration.
Board = {Fresh InitBoard}
%% The core constraints:
{ForAll {Rows Board} FD.distinct}
{ForAll {Columns Board} FD.distinct}
{ForAll {Boxes Board} FD.distinct}
%% Search if necessary.
{FD.distribute ff {Flatten Board}}
end
end
 
%% Returns a list of solutions for the given board.
fun {Solve Board}
{SearchAll {GetScript Board}}
end
 
in
 
{Browse {Solve Board1}.1} %% Tip: make browser window smaller to read the solution.</lang>
 
=={{header|Python}}==
Anonymous user