Skip to main content
1 of 5
Syed
  • 62.9k
  • 5
  • 48
  • 103

Partitioning a list based on a criteria for sublists

SeedRandom[1]; alist = RandomInteger[{1, 10}, 20] 

{2, 5, 1, 8, 1, 1, 9, 7, 1, 5, 2, 9, 6, 2, 2, 2, 4, 3, 2, 7}

I would like to divide this list into sublists (starting at the left) such that Total of each sublist remains less than 20. The output would look like:

{{2, 5, 1, 8, 1, 1}, {9, 7, 1}, {5, 2, 9}, {6, 2, 2, 2, 4, 3}, {2, 7}}

What are some of the idiomatic ways of doing so in Mathematica? Thanks for your help.

Syed
  • 62.9k
  • 5
  • 48
  • 103