One needs a function to check whether a list number is repeating, this function is benadonC
:
In[146]:= Clear[r, s, t, cache, benadonC, pred]
r = {1, 3, 8};
s = {2, 7};
t = {0, 4, 5, 9};
benadonC[l_List, o_Integer] := If[(* Print["elem = ",l]; *)pred == l,
0,(* else *)
pred = l;
If[(* Print["cache: ", cache,"| o = ",o]; *)
IntersectingQ[cache, {o}],
cache = {};
pred = {\[Infinity], \[Infinity]};
1, (* else *)
cache = Flatten[{cache, {o}}];
0
]
]
it uses two global variables, cache
and pred
and then it's as easy as
In[151]:= cache = {}; pred = {\[Infinity], \[Infinity]};
First /@ (Transpose /@ SplitBy[SortBy[
Join[Transpose[{r, ConstantArray[1, Length[r]]}],
Transpose[{s, ConstantArray[2, Length[s]]}],
Transpose[{t, ConstantArray[3, Length[t]]}]], First],
benadonC[#, Last[#]] &])
Out[152]= {{0, 1, 2}, {3, 4}, {5, 7, 8}, {9}}
uncomment the print statements to see how SplitBy
visits the elements.
By the way, benadonC
has an error if one of the lists contains repeated elements:
Set
r = {1, 3, 8, 3};
to get
In[18]:= cache = {}; pred = {\[Infinity], \[Infinity]};
First /@ (Transpose /@
SplitBy[SortBy[Join[Transpose[{r, ConstantArray[1, Length[r]]}],
Transpose[{s, ConstantArray[2, Length[s]]}],
Transpose[{t, ConstantArray[3, Length[t]]}]], First],
benadonC[#, Last[#]] &])
Out[19]= {{0, 1, 2}, {3, 3, 4}, {5, 7, 8}, {9}}
but the correct result is
{{0, 1, 2}, {3}, {3, 4}, {5, 7, 8}, {9}}
that flaw comes from the repetition check. Can you fix it?