16

Just need a little help with the GatherBy / SplitBy function(s).

I have a list of random numbers here:

{8, 4, 2, 1, 9, 4, 2, 1, 5, 2, 1, 3, 1, 2, 11, 4, 2, 1, 5, 2, 1, 3, \
1, 2, 7, 2, 1, 3, 1, 2, 5, 1, 2, 4, 15, 4, 2, 1, 5, 2, 1, 3, 1, 2, 7, \
2, 1, 3, 1, 2, 5, 1, 2, 4, 11, 2, 1, 3, 1, 2, 5, 1, 2, 4, 9, 1, 2, 4,
  8}

How can I write a function with a look-ahead? I want to gather the numbers so it splits whenever it the next number is larger than the current one? (spaced for clarity):

{{8, 4, 2, 1},
{9, 4, 2, 1},
{5, 2, 1},
{3, 1},
{2},
{11, 4, 2, 1},
...}

Tried and failed:

SplitBy[%, Greater]
Mr.Wizard
  • 271,378
  • 34
  • 587
  • 1,371
Mr. Demetrius Michael
  • 1,211
  • 10
  • 15

2 Answers2

13

You need Split:

Split[list, Greater]

SplitBy doesn't work here because the specified function is applied to each element separately before doing a normal Split. What you want is a pair-wise comparison with a custom comparator, which is what Split does.


Looking at this again you may want GreaterEqual to group identical elements in the same list:

Split[{2, 1, 1, 7, 5, 5, 5, 6, 0}, GreaterEqual]
{{2, 1, 1}, {7, 5, 5, 5}, {6, 0}}

For fun I tried to do this operation without Split. Since I was having fun I used Do rather than Module to localize symbols i and x.

split = Last @ Reap @ Do[If[n > x, i++]; Sow[x = n, i], {i, 1}, {x, 1}, {n, #}] &;

split @ {2, 1, 1, 7, 5, 5, 5, 6, 0}
{{2, 1, 1}, {7, 5, 5, 5}, {6, 0}}
Mr.Wizard
  • 271,378
  • 34
  • 587
  • 1,371
11

Use Split[list,Greater] instead of SplitBy[list,Greater].

Leonid Shifrin
  • 114,335
  • 15
  • 329
  • 420
Andrzej Kozlowski
  • 2,839
  • 19
  • 20
  • 2
    It took me a while to answer this because my first attempts were all too short. Why do answers have to be at least 30 characters long? – Andrzej Kozlowski Mar 23 '12 at 21:04
  • 2
    To prevent spam, I guess. Also, chances are that such answers will not be very informative. The model was first designed for StackOverflow, and many popular languages are more verbose than Mathematica. – Leonid Shifrin Mar 23 '12 at 21:20