Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

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]
share|improve this question

2 Answers 2

up vote 10 down vote accepted

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}}
share|improve this answer

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

share|improve this answer
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

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.