Skip to main content
2 of 2
Fix patterns after suggestion by Ali Hashmi
Sjoerd Smit
  • 24.8k
  • 48
  • 80

So if I understand correctly, you want to group the consecutive pairs ({_Integer, _Integer}) at at the first level. Is that correct? In that case, this should probably do the trick:

FixedPoint[
  Replace[#,
    {x1___, 
     x : Longest @ Repeated[{_Integer, _Integer}, {2, \[Infinity]}], 
     x2___} :> {x1, {x}, x2},
    {0}
  ]&,
  {{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}}
]

If you want to apply this at lower levels, you can change the level spec of the Replace. If you want to find other elements that are not lists (instead of just _Integer), you can go with something like {Except[_List], Except[_List]}

Hope this helps.

Sjoerd Smit
  • 24.8k
  • 48
  • 80