I'm currently implementing an prolog program to calculate the shortest path between two points. The framework exists already in a Java project. As a requirement the path must be implemented in prolog. Therefore I use gnu.prolog (http://www.gnu.org/software/gnuprologjava/)
Out of java I call searchPath(1,5,Path)
which will return Path=[5,4,3,2,1]
Here is my prolog code:
:- dynamic(path/3).
findPath( [Goal | Rest], Goal, Temp, Temp, [Goal | Rest]).
findPath( [A | Rest], Goal, Cost, Temp, Path) :-
path(A,B,C),
\+member(B, [A | Rest]),
NewCosts is (Temp + C),
findPath([B, A | Rest], Goal, Cost, NewCosts, Path).
searchPath(Start,Goal,Path_to_goal) :-
findPath([Start], Goal, Cost1, 0, Path),
findPath([Start], Goal, Cost2, 0, Path2),
Cost1=<Cost2,
Path_to_goal = Path.
I have two issues with that:
The
searchPath
method should return the shortest path. However it does NOT. This results in the fact that my ghost "decides" to switch direction at some point resulting in the ghost jittering from left to right.My prolog code takes up to 6 seconds to return a result. I don't have to tell you that this is far too much time. However sometimes prolog only needs 19ms. I wasn't able to figure out on which circumstances this depends on. For example a path list containing 99 elements takes 19ms to calculate but the 6 seconds were spent on a list containing only 38 elements.
Can you suggest any improvements?
Thanks for your help in advance!