Given a list
list = {1,2,2,2,2,5,1,3,2,6,6,6,6,6,6,6,6,6,6,6,10,-3};
how to find the longest constant sublist (or equivalently the element and the number of times it is repeated)?
(in this example, {6,6,6,6,6,6,6,6,6,6,6} or {6,11})
Answer
Concisely and reasonably efficiently:
Last @ Sort @ Split @ list
{6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6}
More efficiently:
# ~Extract~ Ordering[#, -1] & @ Split @ list
{6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6}
Multiple longest runs:
longestRuns[x_List] :=
With[{sp = Split[x]},
sp ~Extract~ Position[#, Max@#] &[Length /@ sp] & @ x
]
{1, 2, 2, 3, 4, 4, 5, 6} // longestRuns
{{2, 2}, {4, 4}}
Less efficiently but having fun with patterns:
list /. {___, seq : Longest[x_ ..], ___} :> {seq}
{6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6}
Comments
Post a Comment