% puzzle.pro
%   A solution to Sam's Silly problem

% del(X, L, M) holds when M is the result of deleting X from L.
%   (Used in the definition of perm.)
del(X, [X|Xs], Xs).
del(X, [Y|Ys], [Y|Xs]) :- del(X, Ys, Xs).

% perm(P, L) holds if P is a perm of L.  Given L, it generates P.  Given
%   P, it may not generate L.  Note that if L is in order, the permutations
%   are generated in lexicographic order from first to last.
perm([], []).
perm([X|Xs], L) :- del(X, L, M), perm(Xs, M).

% value(Digits, D) holds if D is the value of the list of digits.
value([D], D).
value([D0,D1|Digits], D) :- Tmp is D0*10 + D1, value([Tmp|Digits],D).

% solution(X) holds if X is a solution to the problem.
solution([X3,X2,X1,X0]) :- 
  perm([X3,X2,X1,X0,Y4,Y3,Y2,Y1,Y0],[1,2,3,4,5,6,7,8,9]),
  value([X3,X2,X1,X0],X),
  value([Y4,Y3,Y2,Y1,Y0],Y),
  % write([X,Y]), nl,
  Y is 2*X.
