Logic Puzzle in Prolog - using lists

后端 未结 2 932
情深已故
情深已故 2020-12-21 13:03

I am trying to solve the following problem in Prolog, and I think I have coded it right, but my queries simply return false. Any advice on what to change? The problem is as

2条回答
  •  清酒与你
    2020-12-21 13:33

    I've tried to improve readability, using a DCG to pass the state around (look for 'Implicitly passing states around' in this page), so this snippet is very different than your solution.

    You can see that negative knowledge is espressed in two different ways: where people is involved, we can directly use \=, since names are always instantiated, but for other values, like kind(brad, K), I use {dif(K, wheat)}, since K could be not instantiated yet.

    state(S), [state(T)] --> [state(T)], {member(S, T)}.
    
    kind(P, K)  --> state([P, K, _, _, _]).
    topping(P, T)   --> state([P, _, T, _, _]).
    flavor(P, F)    --> state([P, _, _, F, _]).
    size(P, S)  --> state([P, _, _, _, S]).
    
    
    hint1 -->
      kind(brad, K), {dif(K, wheat)}, topping(brad, plain), size(walt, small).
    hint2 -->
      size(P1, medium), size(P2, medium), {P1 \= P2},
      flavor(P1, hazelnut), topping(P2, peanut_butter).
    hint3 -->
      kind(P, onion), flavor(P, french_vanilla), size(P, S), {dif(S, small)}.
    hint4 -->
      size(P1, large), flavor(P2, amaretto), kind(P3, wheat), topping(P4, egg_bacon),
      {forall(select(X, [joe,P1,P2,P3,P4], Ps), maplist(\=(X), Ps))}.
    hint5 -->
      kind(rick, K), {dif(K, blueberry)}, flavor(rick, columbian),
      kind(P, cheddar), flavor(P, amaretto), {P \= walt}.
    hint6 -->
      topping(P1, cream_cheese), kind(P2, blueberry), {P1 \= P2}, size(P1, large),
      kind(P, sesame), topping(P, butter), {P \= carlos}.
    
    bagels(Sol):- Sol =
        [[brad,_,_,_,_],
         [walt,_,_,_,_],
         [joe,_,_,_,_],
         [rick,_,_,_,_],
         [carlos,_,_,_,_]],
      phrase((hint1, hint2, hint3, hint4, hint5, hint6), [state(Sol)], _).
    

    Alas, I get too much solutions... maybe there is a bug in my hints' translation, or the all_different should be applied to all attributes as well, as done for hint n.4

    ?- aggregate(count,S^bagels(S),N).
    N = 7.
    

提交回复
热议问题