Skip to content

Instantly share code, notes, and snippets.

@pierre-dargham
Created June 17, 2016 13:53
Show Gist options
  • Save pierre-dargham/144cbac6853b14531943ece0239df1d4 to your computer and use it in GitHub Desktop.
Save pierre-dargham/144cbac6853b14531943ece0239df1d4 to your computer and use it in GitHub Desktop.
Oz Constraint logic programming : 2016-03-21 Exercice 2 (Queens)
% Author: Pierre Dargham
% Author-URI : https://github.com/pierre-dargham
declare
fun {Board Width}
proc {Script Solution}
% Board and Cells
Size = Width*Width
Cells = {FD.tuple cells Size 0#2}
Count = {FD.int 0#Size}
Whites
Blacks
% Board mathematics
Up = ~Width
Right = 1
Bottom = Width
Left = ~1
Offsets = [Up Up+Right Right Right+Bottom Bottom Bottom+Left Left Left+Up]
% Utils
fun {IsWhite Cell}
Cell == 1
end
fun {IsBlack Cell}
Cell == 2
end
fun {NextCell I Offset}
J = I + Offset
in
if J < 1 then 0
elseif J > Size then 0
elseif Cells.J == 0 then {NextCell J Offset}
else Cells.J
end
end
in
% Solution
Solution = solution(board: Cells count: Count)
% Distribution
{FD.distribute ff Cells}
% Whites and blacks
Whites = {Record.filter Cells IsWhite}
Blacks = {Record.filter Cells IsBlack}
% Propagators (blacks and whites sizes)
Count =: {Record.width Whites} + {Record.width Blacks}
{Record.width Whites} =: {Record.width Blacks}
% Propagators (peace) - One by one :
%{Record.forAllInd Whites proc {$ I C} {NextCell I Up} \=: 2 end}
%{Record.forAllInd Whites proc {$ I C} {NextCell I Up+Right} \=: 2 end}
%{Record.forAllInd Whites proc {$ I C} {NextCell I Right} \=: 2 end}
%{Record.forAllInd Whites proc {$ I C} {NextCell I Right+Bottom} \=: 2 end}
%{Record.forAllInd Whites proc {$ I C} {NextCell I Bottom} \=: 2 end}
%{Record.forAllInd Whites proc {$ I C} {NextCell I Bottom+Left} \=: 2 end}
%{Record.forAllInd Whites proc {$ I C} {NextCell I Left} \=: 2 end}
%{Record.forAllInd Whites proc {$ I C} {NextCell I Left+Up} \=: 2 end}
% Propagators (peace) - All together :
%{Record.forAllInd Whites proc {$ I C} {List.forAll Offsets proc {$ Offset} {NextCell I Offset} \=: 2 end} end}
end
% Sort function
proc {Order A B}
A.count <: B.count
end
in
% Return the best solution
{SearchBest Script Order}
end
% Example 1
{Browse {Board 3}}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment