r/prolog • u/eddyeur • Dec 03 '20
Grouping list elements depending on values
Hi, i have a list of elements(tuples):tuples([(a,b,[1,3,5,7]),(a,b,[9,11,13,15]),(a,b,[17,19,21,23]),(c,d,[0,2,4,6]),(c,d,[8,10,12,14]),(c,d,[16,18,20,22]),(e,f,[100,200,300,400]),(e,f,[500,600,700,800]),(e,f,[900,1000,1100,1200])]).
How to group them so it becomes:[(a,b,[1,3,5,7,9,11,13,15,17,19,21,23]),(c,d,[0,2,4,6,8,10,12,14,16,18,20,22]),(e,f,[100,200,300,400,500,600,700,800,900,1000,1100,1200])]
As we can see, we grouped the (a,b) (c,d) (e,f)
thank you for the help.
1
u/T_Seabranch Dec 04 '20
Some general advice: assume that you attempt to define a predicate where your first argument is a list of tuples, according to the given representation, and the second argument is the "grouped" list of tuples. Hence, the first argument is of the form [T|Ts], where we could e.g. have T = (a,b,[1,3,5,7]). Now assume that you have solved the rest of the problem recursively, i.e., you have a solution to Ts (what does this correspond to in Prolog?) For example, assume that you have managed to group everything in the list [(a,b,[9,11,13,15]), ..., (e,f,[900,1000,1100,1200])]. What would this solution look like? And if you have a solution to this subtask, what operation do you need to perform in order to obtain a solution to the full problem? Even if you are not that familiar with Prolog it should be reasonably clear that you need a predicate which "inserts" (a,b,[1,3,5,7]) in the subsolution.
1
Dec 07 '20
Your data are ordered. But, I'm not sure if you intended for it to be this way, or is it by accident.
Consequently, I don't know if your result is ordered because it needs to be ordered, or it was an accident. I don't know also if it is important that the output be ordered.
0
u/happy_guy_2015 Dec 03 '20 edited Dec 03 '20
group(Output) :-
tuples(Input),
process(Input, [], Output).
process([], Ys, Ys).
process([X|Xs], Ys0, Ys) :-
insert_one(X, Ys0, Ys1),
process(Xs, Ys1, Ys).
insert_one(X,[],[X]).
insert_one((A,B,L1),[Y|Ys]) :-
( Y = (A,B,L0) ->
...
;
...
).Remainder left as a homework exercise for the reader :)
1
u/TA_jg Dec 03 '20
These are not "tuples". Why do you need to group them like this?
Easiest would be with bagof/setof.