Hi, I'm having trouble writing a prolog program which does the following:

Say I'm given a map of 3 different points; Point A, point B and point C. Point A is connected to point B and point B is connected to point C, if you want to travel from point A to point C, you cannot move there directly, you have to travel through point B.

I've wrote a program which does this, but I'm unsure how I can implement some form of count variable which counts the number of 'movements'. For example, a journey from point A to point C would take two movements; point a to b, then point b to c.

``````/*--------------
connections between points
--------------*/

link(a,b).
link(b,c).

/*--------------
logic carried out to connect the movements.
--------------*/

movesto(A,B):- link(A,B).
movesto(A,B):- link(A,C), link(C,B).

/*-----------
layout of count arguement
--------------*/

count(A,B,N):-
``````

Thanks in advance.

Edited by nostalgia: typo

2
Contributors
3
Replies
4
Views
5 Years
Discussion Span
Last Post by nostalgia

We can carry a count with us as we move, this works for movesto(a,e, Dist) but crashes my GNU-Prolog for impossible case movesto(c,e), I do not know what should be changed:

``````/*--------------
connections between points
--------------*/

link(a,b).
link(b,c).
link(b,d).
link(d,e).

/*--------------
logic carried out to connect the movements.
--------------*/

movesto(A,B,1):- link(A,B).
movesto(A,B,2):- link(A,C), link(C,B).
movesto(A,B,Dist):- movesto(A,C,Dist1), movesto(C,B,Dist2), Dist is Dist1 + Dist2.
``````

Edited by pyTony: Notice on crash

The first statement must be link to reduce search:

``````/*--------------
connections between points
--------------*/

link(a,b).
link(b,c).
link(b,d).
link(d,e). link(c,f). link(f,h).

/*--------------
logic carried out to connect the movements.
--------------*/

movesto(A,B,1):- link(A,B).
movesto(A,B,Dist):- link(A,C), movesto(C,B,Dist1), Dist is Dist1 + 1.

``````
``````| ?- movesto(b,X,D).

D = 1
X = c ? ;

D = 1
X = d ? ;

D = 2
X = f ? ;

D = 3
X = h ? ;

D = 2
X = e ? ;

(31 ms) no
| ?-
``````

Edited by pyTony: usage

Thanks, that second reply worked!

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.