1

i have connections between cities like

connection(London,Sziget).
connection(Sziget,Kairo).

so i want to create a predicate to find if there is a possible route between two cities even passing through other cities first.

Input example: route(London,Kairo).
       result: true

Up to this point i have created this recursive code that works.

route(W,Z):-connection(W,Z).
route(W,Z):-connection(W,Y),route(Y,Z).

But i also want to calculate the total cost of the route if the cost between two cities is 100 and for every other city passing is 50 more.

Input example: route(London,Kairo).
       result: true 150

Any help appreciated.

lurker
  • 56,987
  • 9
  • 69
  • 103
cavla
  • 118
  • 3
  • 11
  • 1
    You really want a predicate that has three arguments: the two cities and the cost. That way you have an argument to hold the cost. You also need to show example facts as it's unclear from your problem statement how cost is defined or determined. – lurker Nov 28 '14 at 13:29

1 Answers1

0

It sounds like your cost is: 100 + 50 per intermediate city?

If that's the case, you want something like

route(W, Z, 100) :- connection(W, Z).
route(W, Z, Cost) :- connection(W, Y), route(Y, Z, Cost2), Cost is Cost2+50.

That will evaluate to 100 once the direct link is found, or add 50 to the cost every time you have to go via an intermediate.

In that case, your input would be

route(London, Kairo, Cost).

the result would be

Cost = 150

which would imply that a route was found. If you actually need the 'true' part, that'll be a little trickier.

ABigFatJerk
  • 16
  • 1
  • 6