私は Mat のソリューションが好きですが、問題を解決するには、「and」と「or」を使用して論理式を記述します。
a、b、c および d は、[0,0]、[0,1]、[1,0]、および [1,1] で記号化できます。
(M1 = N1 および M2 = N2) の場合、2 つの数値 M と N は等しい
(M1 \= N1) または (M2 \= N2) (または not(equals) ) の場合、2 つの数値は異なります。
含意 u => v は not(u) または v に変換されます
したがって、次のようになります。
:- use_module(library(clpb)).
:- use_module(library(lambda)).
or(A,B,A+B).
and(A,B,A*B).
% two numbers are equal
equal(A, B, Eq) :-
foldl(\X^Y^Z^T^and(Z, (X =:= Y), T), A, B, 1, Eq).
% two numbers are different
different(A, B, Diff) :-
equal(A,B,Eq),
Diff = ~Eq.
% foldl(\X^Y^Z^T^or(Z, (X =\= Y), T), A, B, 0, Diff).
puzzle :-
A = [0,0],
B = [0,1],
C = [1,0],
D = [1,1],
W = [_,_],
X = [_,_],
Y = [_,_],
Z = [_,_],
% If a is not x, then c is not y.
% (a is x) or (c is not y)
equal(A, X, Eq1),
different(C, Y, Di1),
or(Eq1, Di1, P1),
% If b is either y or z, then a is x.
% (b is not y) and (b is not z) or (a is x)
different(B, Y, Di2),
different(B, Z, Di3),
equal(A, X, Eq2),
and(Di2, Di3, P2),
or(Eq2, P2, P3),
% If c is not w, then b is z.
% (c is w) or (b is z)
equal(C, W, Eq3),
equal(B, Z, Eq4),
or(Eq3, Eq4, P4),
% If d is y, then b is not x.
% (d is not y) or (b is not x)
different(D, Y, Di4),
different(B, X, Di5),
or(Di4, Di5, P5),
% If d is not x, then b is x.
%(d is x) or (b is x)
equal(D, X, Eq5),
equal(B, X, Eq6),
or(Eq5, Eq6, P6),
% we must express that W,X,Y,Z are differents
% W is different from X, Y, Z
foldl(W +\R^S^T^(different(W, R, U),
and(S, U, T)),
[X,Y,Z], 1, Dif1),
% X is different from Y, Z
foldl(X +\R^S^T^(different(X, R, U),
and(S, U, T)),
[Y,Z], 1, Dif2),
% Y is different from Z
different(Y, Z, Dif3),
% now we join all these expressions with an and
Expr = *([P1,P3,P4,P5,P6, Dif1,Dif2, Dif3]),
% we ask Prolog to count the number of solutions
sat_count(Expr, N),
writeln(N : ' solution(s)'),
% we ask Prolog to satisfy the expr
sat(Expr),
maplist(writeln, [A, B, C, D]), nl,
maplist(writeln, [W, X, Y, Z]).
我々が得る :
?- puzzle.
1: solution(s)
[0,0]
[0,1]
[1,0]
[1,1]
[1,0]
[0,1]
[0,0]
[1,1]
true.