Message Boards Message Boards

0
|
4101 Views
|
2 Replies
|
0 Total Likes
View groups...
Share
Share this post:

Which pattern groups these sublists together?

I have a sequence given below:

seq = {{1, 2}, {2, 1}, {2, 2}, {3, 2}, {3, 4}, {4, 2}, {5, 1}, {6,2},
{7, 3}, {8, 4}, {9, 2}, {10, 2}, {10, 3}, {10, 4}, {10,5}, {11, 2}}

I split the list according to the first element

splitlist = SplitBy[seq, First]
{{{1, 2}}, {{2, 1}, {2, 2}}, {{3, 2}, {3, 4}}, {{4, 2}}, {{5,1}},
{{6, 2}}, {{7, 3}}, {{8, 4}}, {{9, 2}}, {{10, 2}, {10,3}, {10, 4}, {10, 5}}, {{11, 2}}}

then decreasing the brackets by 1

splitlist //. {x_} :> x

{{1, 2}, {{2, 1}, {2, 2}}, {{3, 2}, {3, 4}}, {4, 2}, {5, 1}, {6,2}, {7, 3},
{8, 4}, {9,2}, {{10, 2}, {10, 3}, {10, 4}, {10, 5}}, {11, 2}}

Now i wish to find a repeated rule (//.) such that i can group all the consecutive lists of 2 elements together into a single list i.e.

{... {{4, 2}, {5, 1}, {6,2}, {7, 3},{8, 4}, {9,2}} ....} 

Or

{{1, 2}, {{2, 1}, {2, 2}}, {{3, 2}, {3, 4}}, {{4, 2}, {5, 1}, {6,2}, {7, 3},{8, 4},{9,2}}, 
{{10, 2}, {10, 3}, {10, 4}, {10, 5}}, {11, 2}} 

Any pattern that can group sublists of elements 2 when they appear consecutively?

POSTED BY: Ali Hashmi
2 Replies

I would do the following:

lst = {{1, 2}, {{2, 1}, {2, 2}}, {{3, 2}, {3, 4}}, {4, 2}, {5, 1}, {6,
    2}, {7, 3}, {8, 4}, {9, 2}, {{10, 2}, {10, 3}, {10, 4}, {10, 5}}, {11, 2}};

In[2]:= Cases[lst, {x_Integer, y_Integer}]

Out[2]= {{1, 2}, {4, 2}, {5, 1}, {6, 2}, {7, 3}, {8, 4}, {9, 2}, {11, 2}}
POSTED BY: Neil Singer

Probably the //. route is not a good idea: because it will go on forever:

... ,{4, 2}, {5, 1}, {6,2}, {7, 3},{8, 4}, {9,2},...

will turn in to:

... ,{{4, 2}, {5, 1}, {6,2}, {7, 3},{8, 4}, {9,2}},...
... ,{{{4, 2}, {5, 1}, {6,2}, {7, 3},{8, 4}, {9,2}}},...
... ,{{{{4, 2}, {5, 1}, {6,2}, {7, 3},{8, 4}, {9,2}}}},...

unless you put a lot of constraint on it using Depth et cetera, a functional approach is a better solution.

What is your end goal? Starting from seq, what do you want to achieve?

POSTED BY: Sander Huisman
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