0

I have this problem of connected stations

connected(ataba,naguib).
connected(naguib,sadat).
connected(sadat,opera).
connected(opera,dokki).

and i should show the full path taken by the metro, from a source station to a destination

path(ataba,dokki,Z). 
Z = [[ataba, naguib], [naguib, sadat], [sadat, opera], 
[opera, dokki]] . 

i tried to do this :

addlast(X,[],[X]).
addlast(X,[H|T],[H,NewT]):-
addlast(X,T,NewT).

path(X,Y,L) :- connected(X,Y),addlast([X|Y],L,R).

path(X,Y,L):-
    connected(X,Z),
    addlast([X,Z],L,R),
    path(Z,Y,R).

when i tried to trace i noticed i have a problem with the stopping condition , i dont know how to solve it ,any advice or insights would be very helpful.

lurker
  • 56,987
  • 9
  • 69
  • 103
Ashenn
  • 11
  • 3
  • I think you've complicated the problem with `addlast/3`. You really just need `path(Start, Dest, [[Start,Dest]]) :- connected(Start, Dest)` for the simple case, and then `path(Start, Dest, [[Start, Waypoint]|Path]) :- dif(Dest, Waypoint), connected(Start, Waypoint), path(Waypoint, Dest, Path).`. This will work great as long as you don't have any "loops" in your path. If you have a loop, then you'll need yet another argument keeping track of your waypoints and make sure you don't follow a waypoint if you did previously. – lurker Mar 25 '18 at 14:50
  • Got that, thanks for the help ! – Ashenn Mar 25 '18 at 20:31

0 Answers0