Laborator 9

Laborator 9

:-dynamic(node/1).

:-dynamic(edge/3).

edge(a,b,4).

edge(a,c,9).

edge(b,c,7).

edge(b,d,8).

edge(d,c,10).

node(a).

node(b).

node(c).

node(d).

menu :- write("Your option:\n

1. Insert a node\n

2. Delete a node\n

3. Insert an edge\n

4. Delete an edge\n

5. Show the graph\n

6. Show the nodes\n

7. Calculate shortest path from node A to node B\n

8. Exit\n"),

read(Opt),

option(Opt).

option(1) :- write("Type the node you want to insert:\n"),

read(Node),

assert(node(Node)),

menu.

option(2) :- write("Type the node you want to delete:\n"),

read(Node),

retractall(node(Node)),

retractall(edge(Node,_,_)),

retractall(edge(_,Node,_)),

menu.

option(3) :- write("Type the first node:\n"),

read(Node1),

write("Type the second node:\n"),

read(Node2),

write("Type the weight of the edge:\n"),

read(Weight),

assert(node(Node1)), assert(node(Node2)),

assert(edge(Node1,Node2,Weight)),

menu.

option(4) :- write("Type the first node:\n"),

read(Node1),

write("Type the second node:\n"),

read(Node2),

retractall(edge(Node1,Node2,_)),

retractall(node(Node1)),retractall(node(Node2)),

menu.

option(5) :- findall([X,Y,Z],edge(X,Y,Z),List),

write(List),nl,

menu.

option(6) :- findall([X],node(X),List),

write(List),nl,

menu.

option(7) :- write("Type the first node:\n"),

read(Node1),

write("Type the second node:\n"),

read(Node2),

uniq_shortest_path(Node1,Node2 ,MinCost, Path),

write("Mincost: "), print(MinCost),nl,

write("Path: "), write(Path),nl,

menu.

option(8).

path(X, Y, N, Path) :- path(X, Y, N, [], Path).

path(X, Y, N, Seen, [X]) :- \+ memberchk(X, Seen),edge(X, Y, N).

path(X, Z, N, Seen, [X|T]):- \+ memberchk(X, Seen),edge(X, Y, N0),

path(Y, Z, N1, [X|Seen], T),

\+ memberchk(X, T),

N is N0 + N1.

uniq_shortest_path(X, Y, MinCost, Path) :- path(X, Y, MinCost, Path),

\+ (path(X, Y, LowerCost, OtherPath),

OtherPath \= Path,

LowerCost < MinCost).