Search code examples
recursionprologtransitive-closure

Find if there is a connection between two places and calculate cost


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.


Solution

  • 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.