1

I have the following graph:

GRAPH

My goal is to get all the direct connections of a certain node and all of the nodes that are not connected with a certain node for example:

connections(1,X).

X=3;

X=4;

X=5;

X=6.

noConnections(1,X).

X=2.

This is my code:

% knowledge base

path(1, 6).
path(1, 5).
path(1, 4).
path(1, 3).
path(6, 5).
path(5, 4).
path(4, 2).
path(2, 3).

% rules

connections(X,Y) :- path(X,Y) ; path(Y,X).
noConnections(X,Y) :- \+path(X,Y).

As you can see I succesfully did connections but cant find out how to do it for noConnections

Guy Coder
  • 24,501
  • 8
  • 71
  • 136
I'm not human
  • 544
  • 1
  • 9
  • 30

2 Answers2

2

One way :

connected(X, Y) :-
    path(X,Y);path(Y,X).

% fetching all nodes of the database
collectAllNodesButX(X, L) :-
    setof(A, B^(path(A,B);path(B,A)), L1),
    select(X, L1, L).

% main predicate
notConnected(X, L) :-
   collectAllNodesButX(X,Nodes),
   % we exclude all nodes that succeed the predicate connected/2
   findall(Y, (member(Y, Nodes), \+connected(X, Y)), L).

Now, we get :

?- notConnected(1, L).
L = [2] .

?- notConnected(X, [2]).
X = 1 .
joel76
  • 5,565
  • 1
  • 18
  • 22
0

You can use the not(Goal) predicate. You can say not(path(X,Y)); not(path(Y,X)). which is just the inversion of your goals. If the node directly connects to whichever node you are checking for, the result is false. No connections returns true then.

G_V
  • 2,396
  • 29
  • 44