如何防止序言中的重复 [英] How can I prevent duplicates in prolog

查看:112
本文介绍了如何防止序言中的重复的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的多解决问题出现是由于Prolog的回溯循环了目标。虽然我知道在技术上,每个提供的解决方案是正确的,但对我来说并不有用。有没有办法删除重复?

My multiple solution problem arises due to Prolog's backtracking looping through the goals. Whilst I understand that, technically, each solution provided is correct, it is not useful to me. Is there a method to remove duplicates?

这是我的代码到目前为止:

Here is my code so far:

flight(london, paris).
flight(paris, amsterdam).
flight(amsterdam, rome).
flight(rome, paris).
flight(rome, rio_de_janeiro).
route_from(A,B) :-
  flight(A,B).
route_from(A,B) :-
  flight(A,R),
  route_from(R,B).

一个示例查询是:

?- route_from(A, paris).
A = london ;
A = rome ;
A = london ;
A = london ;
A = london ;
A = london ;
A = london ;
A = london ;
A = london ;
etc.

请问。

推荐答案

除了返回重复的解决方案外,您还有更大的问题。您的程序就会无限循环,因为图中有循环。

You have a bigger issue other than returning repeated solutions. Your program, as is, will loop indefinitely as there are loops in your graph.

为了避免循环,您可以保留已访问城市的列表:

To avoid loops you may maintain a list of visited cities:

route_from(A,B) :-
  route_from(A,B, []).

route_from(A,B, _) :-
  flight(A,B).
route_from(A,B, Visited) :-
  flight(A,R),
  \+ member(A, Visited),
  route_from(R,B, [A|Visited]).

现在,如果有多种方式去城市,这不会阻止返回重复。您可以使用 setof / 3 + member / 2 收集所有解决方案,而无需重复。

Now, this won't prevent returning duplicates if there are more than one way to go to a city. You can use setof/3 + member/2 to gather all solutions without duplicates.

route_from_without_duplicates(A,B):-
  setof(A-B, route_from(A,B), Routes),
  member(A-B, Routes).

这篇关于如何防止序言中的重复的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆