Search code examples
prologgraph-theorytransitive-closure

Prolog find non related graph nodes


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


Solution

  • 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 .