prolog - List all reachable nodes -


i have predicate bi-directional , tells, whether 1 node connected another. e.g.

has(a, b). has(b, c). has(d, b). 

now list nodes can reached (from specific node) given number of steps.

connected_nodes(a, t, 2).  

should therefore output

t = c  t = d 

my current code looks this:

connected_nodes(a, b, 0) :- write(a). connected_nodes(a, b, n) :-      n > 0, m n - 1,     has(a, x),     connected_nodes(x, b, m). 

this works t = c not t = d, bi-directional relation.

am thinking correctly in terms of recursion or how in other way problem have solved?

your connected predicate seems fine. might have made more sense make base case rely on has, it's you.

however, say has predicate "bi-directional" haven't explicitly created rule indicates this.

the following code "bi-directional" version of code:

has(a, b). has(b, c). has(d, b).  bi_has(x,y) :- has(x,y). bi_has(x,y) :- has(y,x).  connected_nodes(a, b, 0) :- write(a). connected_nodes(a, b, n) :-      n > 0, m n - 1,     bi_has(a, x),     connected_nodes(x, b, m). 

note query returns a possible answer too. makes since, because never explicitly stated don't want return same element after 2 steps.

if don't want behaviour, need keep list of elements visited far (i.e. accumulator), , confirm you're not revisiting elements.


Comments

Popular posts from this blog

account - Script error login visual studio DefaultLogin_PCore.js -

xcode - CocoaPod Storyboard error: -