Monday, February 28, 2011

Path Finding in Prolog

Prolog is a First Order Logic (FOL) interpreter which can be used to solve logic based problems. Logic based solutions are widely needed in Intelligent System Design. 
Using FOL we can create the Knowledge Base (KB) for the problem whish has objects, predicates & functions. After the construction of the KB, by the use of an Resolution algorithm we can logically take decision from the KB.
Prolog uses Backward Chaining resolution algorithm.

Here you can see a program which finds the path between two nodes in a given graph, under the given constraints.

Eg-1: Find the path between the given two nodes?

The graph is defined by the edges as edge(start, end).
After compiling, type the query in the prompt, which will give the results shown.

-------------------------------------------------
%Edge List (Knowledge Base)
edge(1,2).
edge(1,4).
edge(2,4).
edge(3,6).
edge(3,7).
edge(4,3).
edge(4,5).
edge(5,6).
edge(5,7).
edge(6,5).
edge(7,5).
edge(8,6).
edge(8,7).

%Program
path(X,Y,[X,Y]):- edge(X,Y).
path(X,Y,[X|Xs]):- edge(X,W), path(W,Y,Xs).
-------------------------------------------------

%Query
path(1, 7, P).

%Results
Z = [1, 2, 4, 3, 6, 5, 7];
Z = [1, 2, 4, 3, 6, 5, 6, 5, 7];
.........................

Eg-1: Find the path between the given two nodes, where nodes appear in ascending order?

Knowledge Base is the same.

-------------------------------------------------
%Program
path(X,Y,[X,Y]):- edge(X,Y),X<Y.
path(X,Y,[X|Xs]):-edge(X,W), X<W, path(W,Y,Xs).
-------------------------------------------------

%Query
path(1, 7, P).

%Results
Z = [1, 2, 4, 5, 7];
Z = [1, 4, 5, 7]

Eg-3: Find the path between the given two nodes with the given length?

The graph is defined by the edges as edge(start, end, cost).

-----------------------------------------------------------------
%Edge List (Knowledge Base)
edge(1, 2, 3).
edge(1, 4, 5).
edge(2, 4, 2).
edge(3, 6, 6).
edge(3, 7, 5).
edge(4, 3, 7).
edge(4, 5, 4).
edge(5, 6, 8).
edge(5, 7, 1).
edge(6, 5, 2).
edge(7, 5, 2).
edge(8, 6, 3).
edge(8, 7, 4).

%Program
path(X,Y,C,[X,Y]):- edge(X,Y,C).
path(X,Y,C,[X|Xs]):- edge(X,W,C1), plus(C1,C2,C),C2>0, path(W,Y,C2,Xs).
-----------------------------------------------------------------

%Query
path(1, 7, 17, P).

%Results
Z = [1, 2, 4, 3, 7];
Z = [1, 4, 3, 7]