Trying to figure it out, how can I merge output like this one in Prolog:
[[z], [l, e, d], [j, i, d, c, a], [g, f, b], [h, b]]
to get result:
[z]
[l,e,d,j,i,c,a]
[g,f,b,h]
Not sure how to merge multiple lists containing at least one similar character.
I would appreciate any help from more experienced guys, cause I am just beginner and this task is quite tricky.
Thanks.
EDIT
Task is to get from edges defined by user all connected components and print them on output.
For instance user input edges:
data([[z,z],[a,c],[c,d],[d,i],[i,j],[d,e],[e,l],[b,f],[f,g],[b,h]]).
So I'm trying to figure it out how to solve this problem. What I've just did:
data(Edges):-
dbH(Edges),
searching,
print,
retractall(e(_,_)),
retractall(lists(_)).
dbH([]).
dbH([[X, Y] | Body ]) :-
assertz(e(X,Y)),
dbH(Body).
oe(X,Y):-
e(X,Y);
e(Y,X).
searching:-
nextE.
searching([Act | RouteStartAct]):-
nextE([Act | RouteStartAct]).
nextE:-
oe(Act,New),!,
delE(Act,New),
cycle([Act],New).
nextE:-
!.
nextE([Act | RouteStartAct]):-
oe(Act,New),!,
delE(Act,New),
cycle([Act | RouteStartAct],New).
nextE(Act):-
assertz(lists(Act)),
searching.
delE(X,Y):-
retract(e(X,Y));
retract(e(Y,X)).
cycle(Act,New):-
not(mbr(New, Act)), !,
searching([New|Act]).
cycle(Act,New):-
assertz(lists(Act)),
searching.
mbr(Element, [Element|_]).
mbr(Element, [_|Body]) :-
mbr(Element, Body).
print:-
findall(C,lists(C),L),
write(L).
At the end write(L) prints list of lists which I need to further merge based on the similar elements in each list. Like connect parts of one graph together and print them.
EDIT2 The result of this command:
?- data([[a, c], [c, d], [d, i], [i, j], [d, e], [e, l], [b, f], [f, g], [b, h]]).
is
[[j, i, d, c, a], [l, e, d], [g, f, b], [h, b]]
so from this output is obvious, that list [j, i, d, c, a] and [l, e, d] can be merged into one list [j, i, d, c, a, l, e]. Same for the lists [g, f, b] and [h, b], these two lists have common character b , so the output should be [g, f, b, h].
As a result of these two merges final output should look like:
[j, i, d, c, a, l, e]
[g, f, b, h]
Is it more obvious know?
AandBcan be not consecutive? I mean: what do you want fromdata([[a, b], [d], [b, c]])?[[a, b, c], [d]]or[[a, b], [d], [b, c]]? Anyway, if you can show us the expected answer from the given input can be helpfull. - max66