Skip to content

Commit 0ee617e

Browse files
author
Georgi Shopov
committed
Generalise the solution to exercise 10.4
Now it solves the general case -- when the cities and the connections between them form an arbitrary graph. This solution tries not to get into loops and therefore does not generate all solutions when there is a loop (in this case there would be infinitely many solutions).
1 parent 55e400b commit 0ee617e

File tree

1 file changed

+13
-14
lines changed

1 file changed

+13
-14
lines changed

chapter-10/exercises.pl

Lines changed: 13 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -102,23 +102,22 @@
102102
%% ?- route(forbach,metz,Route).
103103
%% Route = [forbach,freyming,stAvold,fahlquemont,metz].
104104

105+
directPath(X, Y) :-
106+
directTrain(X, Y).
107+
108+
directPath(X, Y) :-
109+
directTrain(Y, X).
110+
105111
%% base case
106-
travelBetween(X, Y, [Y]) :- directTrain(X, Y), !.
112+
route(Y, Y, RevL, L) :-
113+
reverse(RevL, L).
107114

108115
%% inductive case
109-
travelBetween(X, Y, [Z | L]) :-
110-
directTrain(X, Z), !,
111-
travelBetween(Z, Y, L).
112-
113-
myRoute(X, Y, [X | L]) :-
114-
travelBetween(X, Y, L), !.
115-
myRoute(X, Y, [Y | L]) :-
116-
travelBetween(Y, X, L), !.
116+
route(X, Y, RevL, L) :-
117+
directPath(X, Z),
118+
not(member(Z, RevL)),
119+
route(Z, Y, [Z | RevL], L).
117120

118121
%% main
119122
route(X, Y, L) :-
120-
myRoute(X, Y, RevL),
121-
reverse(RevL, L).
122-
123-
%% Problem: This only works because the train connetions form a doubly linked
124-
%% list, if it was a proper graph the above algorithm wouldn't work.
123+
route(X, Y, [X], L).

0 commit comments

Comments
 (0)