Let’s say, we have a list of lists:
Table[0, {30}, RandomInteger[{1, 5}]]
which might look like this
{{0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0}, {0, 0}, {0, 0, 0, 0}, {0}, {0, 0}, {0, 0, 0, 0}, {0}, {0}, {0, 0, 0, 0}, {0}, {0, 0, 0}, {0, 0, 0}, {0, 0}, {0, 0, 0, 0}, {0, 0, 0}, {0, 0, 0}, {0, 0, 0}, {0}, {0, 0, 0, 0}, {0, 0, 0}, {0, 0, 0, 0}, {0}, {0}, {0, 0, 0}, {0}, {0, 0, 0, 0}, {0}, {0, 0, 0}}
My function now groups the lists so that each group contains not more than 10 elements if the group gets flattened once. In this case it results in:
{{{0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0}}, {{0, 0}, {0, 0, 0, 0}, {0}, {0, 0}}, {{0, 0, 0, 0}, {0}, {0}, {0, 0, 0, 0}}, {{0}, {0, 0, 0}, {0, 0, 0}, {0, 0}}, {{0, 0, 0, 0}, {0, 0, 0}, {0, 0, 0}}, {{0, 0, 0}, {0}, {0, 0, 0, 0}}, {{0, 0, 0}, {0, 0, 0, 0}, {0}, {0}}, {{0, 0, 0}, {0}, {0, 0, 0, 0}, {0}}, {{0, 0, 0}}}
With group lengths of {10, 9, 10, 9, 10, 8, 9, 9, 3}
.
I am asking myself, if there is a better way to implement it.
RegroupWithListLength[list_, limit_: 10] := Block[
{result = {{}}},
Do[If[
Length[Flatten[result[[-1]], 1]] + Length[list[[i]]] <= limit,
AppendTo[result[[-1]], list[[i]]],
AppendTo[result, {list[[i]]}]],
{i, Length[list]}];
result
]
$\tiny\textit{For the code golfers around ... in my small world, this might be a nice challenge, no?}$
‹νφ«§_^CLX-IχA
? $\endgroup$ – Jason B. Jun 28 '17 at 20:05