Skip to main content
3 of 8
added 664 characters in body
rhermans
  • 37.7k
  • 4
  • 64
  • 156

SequenceSplit, Longest, Plus

I think it's best to take advantage of the built-in SequenceSplit and ask for the Longest pattern with the Condition(/;) that it adds up (Plus) to less than 20 (<20).

SequenceSplit[alist, {Longest[a__]} /; Plus[a] < 20 :> {a}] 

It's reasonably short and idiomatic and doesn't create any lingering definitions. I am looking forward to seeing various other answers. Nice question!

Performance

This is rather slow for long lists, measuring with AbsoluteTiming at various lengths.

ListPlot[ Table[ {l, First@AbsoluteTiming[ SequenceSplit[ RandomInteger[{1, 10}, l] , {Longest[a__]} /; Plus[a] < 20 :> {a} ]; ] } , {l, 10, 1200, 50} ] , PlotTheme -> "Scientific" , FrameLabel -> {"List length", "Time [s]"} ] 

enter image description here

This is in a rather old i7-4770 CPU @ 3.40GHz

rhermans
  • 37.7k
  • 4
  • 64
  • 156