Message Boards Message Boards

0
|
7626 Views
|
6 Replies
|
1 Total Likes
View groups...
Share
Share this post:
GROUPS:

How do I Split this?

I have different lists which, once joined and sorted, I'd like to split whenever an element from one of the lists appears again. For example:

r = {1, 3, 8}

s = {2, 7}

t = {0, 4, 5, 9}

Joined and sorted: {0, 1, 2, 3, 4, 5, 7, 8, 9}

The output I'm looking for is: {{0, 1, 2}, {3, 4}, {5, 7, 8}, {9}}

How can I do it?

POSTED BY: Fernando Benadon
6 Replies
Posted 9 years ago
POSTED BY: Xavier Roy
POSTED BY: Udo Krause
Posted 9 years ago
POSTED BY: Xavier Roy

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?

POSTED BY: Udo Krause
POSTED BY: Udo Krause
Posted 9 years ago
r = {1, 3, 8, 0};
s = {2, 7, 9};
t = {0, 4, 5, 9};
Split[Sort[Join[r, s, t]], ! SameQ[#1, #2] &]

{{0}, {0, 1, 2, 3, 4, 5, 7, 8, 9}, {9}}

POSTED BY: Michael Helmle
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard

Group Abstract Group Abstract