0

If I have a list of facts about flights, how do I write a predict to return all routes from one city to a list cities one by one? for example, all routes from rome to [moscow, amsterdam].

flight(london,dublin).
flight(rome,london).
flight(rome,paris).
flight(paris,dublin).
flight(berlin,moscow).
flight(paris,amsterdam).
flight(berlin,dublin).
flight(london,newyork).
flight(dublin,newyork).
flight(dublin,cork).
flight(dublin,rome).
flight(dublin,chicago).
flight(amsterdam,hongkong).
flight(london,hongkong).
flight(dublin,amsterdam).
lurker
  • 56,987
  • 9
  • 69
  • 103
Davidw
  • 31
  • 4
  • What have you tried so far? Here's a hint: A route from `A` to `B` might have a direct flight from `A` to `B`, or be a direct flight from `A` to `C` and a route from `C` to `B`. – lurker Nov 22 '17 at 01:55
  • I have created a predict to return all possible routes from one city to one city, e.g trip(rome, london) returns [rome, london], [rome, paris, london] etc. But I don't know how to write a predict to return all possible routes from one city to a list of cities. – Davidw Nov 22 '17 at 02:06
  • All you need is a predicate that succeeds for every route from `A` to `B`. Then use `findall`: `findall( Dest, route(A, Dest), AllDestinations ).` – lurker Nov 22 '17 at 02:17
  • findall will return all possible routes in a list. Is there a way to return each route one by one? – Davidw Nov 22 '17 at 02:27
  • Sorry, your last comment showed results in a list and I misunderstood. Yes, you can do that. Include an argument to `route` which is the "running list" of intermediate destinations. Do a search on this site for `[prolog] routes` and you should be able to find lots of examples. – lurker Nov 22 '17 at 02:48
  • Possible duplicate of [Find all possible paths without revisiting](https://stackoverflow.com/questions/13170401/find-all-possible-paths-without-revisiting) – lurker Nov 22 '17 at 02:51

1 Answers1

0

There exist a path if there is some direct flight:

route(X,Y,L):-
   route(X,Y,L,[X]).

route(X,Y,L,K):-
  flight(X,Y),
  reverse([Y|K],L).

Or if there exist some Z such that Z is connected is X and Z is connected with Y.

route(X,Y,L,E):-
  flight(X,Z),
  \+ member(Z,E),
  route(Z,Y,L,[Z|E]).

If you want to find all path in one list then use findall/3 from prolog predefined predicates.

Luai Ghunim
  • 976
  • 7
  • 14