在 Prolog 中解决逻辑难题

发布于 2024-10-12 14:17:22 字数 1436 浏览 8 评论 0原文

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

她比我温柔 2024-10-19 14:17:22
neigh(Left, Right, List) :- 
        List = [Left | [Right | _]];
        List = [_ | [Left | [Right]]].

zebraowner(Houses, ZebraOwner):-
        member([englishman, _, red], Houses),
        member([spanish, jaguar, _], Houses),
        neigh([_, snail, _], [japanese, _, _], Houses),
        neigh([_, snail, _], [_, _, blue], Houses),
        member([ZebraOwner, zebra, _], Houses),
        member([_, _, green], Houses).


zebra(X) :- zebraowner([_, _, _], X).
neigh(Left, Right, List) :- 
        List = [Left | [Right | _]];
        List = [_ | [Left | [Right]]].

zebraowner(Houses, ZebraOwner):-
        member([englishman, _, red], Houses),
        member([spanish, jaguar, _], Houses),
        neigh([_, snail, _], [japanese, _, _], Houses),
        neigh([_, snail, _], [_, _, blue], Houses),
        member([ZebraOwner, zebra, _], Houses),
        member([_, _, green], Houses).


zebra(X) :- zebraowner([_, _, _], X).
情定在深秋 2024-10-19 14:17:22

我是 Prolog 的新手,但我认为 neigh 的定义不太正确。尝试:

   neigh(2,3,[1,2,3]).

你可以摆脱这个不太有效的问题,因为有两种解决方案,一种是日本拥有的斑马在第二个房子,另一种是斑马在第三宫,而你的代码只找到一个(这足以回答问题:-)。
这段代码给出了 neigh 的正确答案,因此给出了问题的两个答案:

neigh(Left, Right, List) :- 
        List = [Left, Right ,_];
        List = [_, Left, Right]].

但只适用于三栋房子。更通用的实现是:

neigh(Left, Right, List) :- 
        List = [Left , Right | _].
neigh(Left, Right, [_|Tail]) :- 
        neigh(Left, Right, Tail).

I'm new to Prolog, but I think the definition of neigh is not quite right.Try:

   neigh(2,3,[1,2,3]).

You get away with this not quite working because there are two solutions, one with the Japanese owned zebra in the second house, and one with the zebra in the third house and your code only finds one (which is enough to answer the question :-).
This code give the right answers for neigh and hence both answers to the problem:

neigh(Left, Right, List) :- 
        List = [Left, Right ,_];
        List = [_, Left, Right]].

but then only works for three houses. A more general implementation is:

neigh(Left, Right, List) :- 
        List = [Left , Right | _].
neigh(Left, Right, [_|Tail]) :- 
        neigh(Left, Right, Tail).
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文