transitive closure - (Prolog) How to find if a connection exists between 2 predicates -


this have far. need show if 2 stations connected via third station, connected each other

station(hamburg). station(bremen). station(hannover). station(berlin). station(leipzig). station(osnabruck). station(stuttgart). station(fulda). station(munich).  adjacent(hamburg, bremen). adjacent(hamburg, berlin). adjacent(berlin, hannover). adjacent(berlin, leipzig). adjacent(leipzig, fulda). adjacent(fulda, hannover). adjacent(hannover, osnabruck). adjacent(osnabruck, bremen). adjacent(stuttgart, munich).  /* insert clauses here */  adjacent_(x,y) :-adjacent(y,x) . adjacent_(x,y) :-adjacent(x,y) .  connected(x,y) :-adjacent(x,y) . connected(x,z) :-connected(x,y), adjacent_(y,z) . 

your first connected clause fail clause like:

?- connected(bremen, hamburg). 

presumably meant write

connected(x,y) :- adjacent_(x,y) . 

instead.

other above bug, code seems fine. thing i'd add you're not guarding against "cycles". e.g. if trying find if berlin connected fulda, in theory might never there because of following cycle:

berlin -> hannover -> osnabruck -> bremen -> hamburg -> berlin (and on ad infinitum).

therefore include accumulator in code, containing nodes visited far, such don't allow clause succeed if current node appears in node "path".


ps. if you're interested find out whether x , z connected, , not in how many possible ways, explicitly specify cut (i.e. !) @ end of each connected clause.


Comments

Popular posts from this blog

java - SSE Emitter : Manage timeouts and complete() -

jquery - uncaught exception: DataTables Editor - remote hosting of code not allowed -

java - How to resolve error - package com.squareup.okhttp3 doesn't exist? -