Prolog riddle solving

▼魔方 西西 提交于 2019-12-25 04:48:05

问题


The statement :

Four couples in all

Attended a costume ball.

2

The lady dressed as a cat

Arrived with her husband Matt.

3

Two couples were already there,

One man dressed like a bear.

4

First to arrive wasn't Vince,

But he got there before the Prince.

5

The witch (not Sue) is married to Chuck,

Who was dressed as Donald Duck.

6

Mary came in after Lou,

Both were there before Sue.

7

The Gipsy arrived before Ann,

Neither is wed to Batman.

8

If Snow White arrived after Tess,

Then how was each couple dressed?

My code is here , but it returns false :

sol(S):-
    S=[[1,L1,M1,LD1,MD1],
        [2,L2,M2,LD2,MD2],
        [3,L3,M3,LD3,MD3],
        [4,L4,M4,LD4,MD4]],
    member([_,_,matt,cat,_],S),
    member([ALR,_,_,_,bear],S),
    (ALR =:= 1 ; ALR =:= 2),
    not(member([1,_,vince,_,_],S)),
    member([VN,_,vince,_,_],S),
    member([PS,_,_,_,prince],S),
    VN < PS ,
    member([_,_,chuck,witch,donald],S),
    not(member([_,sue,_,witch,_],S)),
    member([MRY,mary,_,_,_],S),
    member([LOU,_,lou,_,_],S),
    member([SUE,sue,_,_,_],S),
    MRY > LOU,
    MRY < SUE,
    member([GPS,_,_,gipsy,_],S),
    member([ANN,ann,_,_,_],S),
    GPS < ANN ,
    not(member([_,_,_,gipsy,batman],S)),
    not(member([_,ann,_,_,batman],S)),
    member([SW,_,_,snowwhite,_],S),
    member([TS,tess,_,_,_],S),
    SW > TS ,
    perm([sue,mary,ann,tess],[L1,L2,L3,L4]),
    perm([matt,lou,vince,chuck],[M1,M2,M3,M4]),
    perm([cat,witch,gipsy,snowwhite],[LD1,LD2,LD3,LD4]),
    perm([donald,prince,batman,bear],[MD1,MD2,MD3,MD4]).




takeout(X,[X|R],R).
takeout(X,[F|R],[F|S]) :- takeout(X,R,S).

perm([],[]).
perm([X|Y],Z) :- perm(Y,W), takeout(X,Z,W).

Any solution ?


回答1:


You should move all your not(...) goals to the very end of the predicate.

not(G) means, "G is impossible to satisfy right now". When tried too early, with many still non-instantiated variables in the lists, it is in fact very often possible to satisfy a goal, and the whole not(...) call will fail right away.

Alternatively, delay the checking of the inequality on a variable until it is instantiated, e.g. in SWI Prolog with freeze/2 (as seen e.g. in this answer).



来源:https://stackoverflow.com/questions/28093020/prolog-riddle-solving

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!