开发者

Adjacency Matrix in prolog

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 tha开发者_如何学Got 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.


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜