0

I am learning Prolog. I am working on an assignment. I have already produced some code, which is partially working. But, somehow it is giving multiple duplicate answers.

The question is:

% Every letter represents a Digit (0,...,9).
% Leading digits (S and M) can not be 0.
%    S E N D
%  + M O R E
%  ---------
%  M O N E Y
% Write a Prolog program that solves the quiz, i.e., that finds the
% appropriate values for S,E,N,D,M,O, ... such that the addition is correct.

The solution I came up with is :

jobs1([0,1,2,3,4,5,6,7,8,9]).

solution1([_,_,S,E,N,D,M,O,R,Y],
     constraints([
        \+ S is 0,
        \+ M is 0,
        0 is (10000*M+1000*O+100*N+10*E+Y -  (1000*S+100*E+10*N+D + 1000*M+100*O+10*R+E)) ])).

puzzle1(Erg) :- write("Puzzle1 "), nl, jobs1(S),
    solution1([_,_|Erg] ,
           constraints(Cs)),permC(S,[_,_|Erg],Cs) .

But, when I run this code, I get answers like this :

7 ?- puzzle1(S).
Puzzle1 
S = [9, 5, 6, 7, 1, 0, 8, 2] ;
S = [9, 5, 6, 7, 1, 0, 8, 2] ;

I know why this happening(Because, I am ignoring the first 2 positions and because of their permutation, the result is showing 2 time). Can you please help to understand how can I remove it without using !(Because, if there are multiple answers, ! will only show the first answer, which is not expected.)

Thanks in advance!

4

1 回答 1

4

Your code tries every permutation of the 10 digits, and reports on each that meets the constraints. You are only showing 8, but there are 2 more, and hence 2 distinct permutations with the same last 8 digits. So you could, for example, add the requirement that the digits you don't care about are in a particular order, so that only 1 permutation would be acceptable.

于 2015-11-10T18:55:48.253 回答