Adjacency Matrix in prolog

2019-07-09 09:23发布

问题:

I need to create an adjacency matrix with graphs vertexes represented as facts: e.g.

graph(a,b).
graph(c,c).
graph(b,c).

I'll need to output the matrix:

0 1 0
0 0 1
0 0 1

I know I should make a list for each line, but problems arise when they're symbols, not numbers, so I don't have any idea how to know the size of that list (if for example there's a graph(e,f). the list must be six numbers long so the f can fit). I don't want the full answer, if you just want to tell me a sketch of what to do, I suppose I'll be fine.

回答1:

I haven't written much Prolog code recently, but this is approximately what I think I would write (not tested):

printedge(X,Y) :-    graph(X,Y), write("1 ").
printedge(X,Y) :- \+ graph(X,Y), write("0 ").

printmatrix :-
    List = [a,b,c,d],
    member(Y, List),
    nl,
    member(X, List),
    printedge(X,Y),
    fail.

Now you only need to get a list of elements somehow.



回答2:

To get a list of all nodes:

node(X) :- graph(X,_).
node(X) :- graph(_,X).
allnodes(Nodes) :-
    setof(X, node(X), Nodes). % removes duplicates

To get the number of nodes:

numnodes(N) :-
    allnodes(Nodes),
    length(Nodes, N).


标签: prolog