1,105,556 Community Members

Prolog - Recursion

Member Avatar
nostalgia
Newbie Poster
8 posts since Aug 2011
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

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.

Member Avatar
pyTony
pyMod
6,104 posts since Apr 2010
Reputation Points: 818 [?]
Q&As Helped to Solve: 1,056 [?]
Skill Endorsements: 42 [?]
Moderator
Featured
 
0
 

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.
Member Avatar
pyTony
pyMod
6,104 posts since Apr 2010
Reputation Points: 818 [?]
Q&As Helped to Solve: 1,056 [?]
Skill Endorsements: 42 [?]
Moderator
Featured
 
1
 

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
| ?- 
Member Avatar
nostalgia
Newbie Poster
8 posts since Aug 2011
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

Thanks, that second reply worked!

Question Answered as of 2 Years Ago by pyTony
You
This question has already been solved: Start a new discussion instead
Post:
Start New Discussion
Tags Related to this Article