pvl
pvl

Reputation: 27

Prolog sum of acalculation

I have some cartesian coordinates definition:

point(a, 5, 1).
point(b, 4, 2).
point(c, 3, 3).
point(d, 2, 4).

And a "route" definition:

route(path1, [a, c, b, d]).

Then I have a function to calculate the distance between two points, like this:

distance(P1, P2, D):-point(P1, X1, Y1), point(P2, X2, Y2),
 Z is ((X2-X1)*(X2-X1))+((Y1-Y2)*(Y1-Y2)),
 Z >= 0,
 D is sqrt(Z).

How can I calculate the full distance of a route?

Also, if I have several routes how can I find the longest one?

Upvotes: 0

Views: 218

Answers (1)

user1812457
user1812457

Reputation:

Edit: should be correct now

First, to find the length of a given route, using the distance function you have provided:

path_len(Path, D) :- route(Path, [First|Points]), path_len(Points, First, 0, D).

path_len([], _Last, Dist, Dist).
path_len([P|Points], Prev, DAcc, Dist) :-
    distance(Prev, P, D),
    NDAcc is DAcc+D,
    path_len(Points, P, NDAcc, Dist).

where DAcc is an accumulator for the distance so far (initialized with 0). You can query this with

?- path_len(path1, D).

If you have several routes defined already (do I understand this correctly?), path_len/2 will calculate the total distance of all of them by backtracking. You can then build distance-path pairs and use keysort/2 to sort them and maybe reverse/2 to put the last one first:

longest_path(Path, Dist) :-
    bagof(D-P, path_len(P, D), DPPairs),
    keysort(DPPairs, Sorted),
    reverse(Sorted, [Dist-Path|_]).

You could have also used last/2 instead of reverse/2 on the last line of the predicate definition:

last(Sorted, Dist-Path).

Upvotes: 1

Related Questions