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]
Answer
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}}
Comments
Post a Comment