卡在 Prolog 问题上。我知道答案(因为我先在纸上做了),但我不知道如何让 Prolog 想出答案。
问题:
比尔每晚都吃点零食,每晚吃不同的水果和不同的坚果。从下面的陈述中,找出比尔上周每个工作日晚上吃了什么零食。
a) 苹果比芒果吃得晚。
b) 香蕉比杏仁和花生吃得晚,但比梨吃得早。
c) 腰果比香蕉和杏早吃,但比花生晚。
d) 杏仁后晚上没有吃山核桃。
e) 比尔吃了一晚核桃。
请注意,问题是关于 5 个工作日晚上(周一至周五),并提到了 5 种水果和 5 种坚果。您的程序应该解决问题并打印出解决方案,这将是一组 5 个三元组,例如(星期一,苹果,山核桃),...(星期五,芒果,核桃)。
显然,这些不是正确的答案,而只是向您展示解决方案的价值。
到目前为止的代码:
before_in_week(X, Y, Days) :-
nth1(Xi, Days, X),
nth1(Yi, Days, Y),
Xi < Yi.
print_solve([Head|Tail]) :-
write(Head),
nl,
print_solve(Tail).
solve(A) :-
% all triples
A = [[day1, fruit1, nut1],
[day2, fruit2, nut2],
[day3, fruit3, nut3],
[day4, fruit4, nut4],
[day5, fruit5, nut5]],
Days = [monday, tuesday, wednesday, thursday, friday],
Days = [day1, day2, day3, day4, day5],
Fruits = [apple,banana,pear,mango,apricot],
permutation(Fruits, [fruit1, fruit2, fruit3, fruit4, fruit5]),
Nuts = [almonds,pecans,cashews,peanuts,walnuts],
permutation(Nuts, [nut1, nut2, nut3, nut4, nut5]),
% clue 1 - mango before apple
fruit5 \= mango,
member([C1,mango,_], A),
member([C2,apple,_], A), before_in_week(C1,C2,Days),
% clue 2 - banana after almonds and peanuts, but before pear
fruit5 \= banana,
member([C1,banana,_], A),
member([C2,pear,_], A), before_in_week(C1,C2,Days),
member([C3,_,almonds], A), before_in_week(C3,C1,Days),
member([C4,_,peanuts], A), before_in_week(C4,C1,Days),
% clue 3 - cashews before banana and apricot, but after peanuts
nut5 \= peanuts,
member([C1,_,cashews], A),
member([C2,_,peanuts], A), before_in_week(C1,C2,Days),
member([C3,banana,_], A), before_in_week(C3,C1,Days),
member([C4,apricot,_], A), before_in_week(C4,C1,Days),
% clue 4 - pecans not night after almonds
nut5 \= almonds,
% clue 5 - ate walnuts one night
print_solve(A).