Update
Per a comment by the OP, here's an updated version that manages sublists of length larger than 10 in the following way. If needed, the first chunk of the offending sublist is appended to the current list to get that list up to a total Flatten
ed length of 10. The rest of the list is partitioned into lists of length 10 plus a list of length the remainder upon division by 10. This last list is then the first sublist used in the next set of sublists.
Here is the klugey, pretty-ugly code. Given time later, I might take a crack at simplifying some of the klugey bits (like that explicit CompoundExpression
and everything associated with it).
partitionByLength[inlist_, len_] := Module[{lst},
Append[#2[[1]], #1] & @@ Reap@Fold[
Which[
Length@Flatten@(lst = Append[#1, #2]) <= len
, lst
, Length[#2] <= len
, Sow[#1]; {#2}
, True
, Sow[Append[#1, #2[[;; len - Length@Flatten@#1]]]]
; CompoundExpression @@ {Sow /@ List /@ Most@#, {Last@#}} &@
Internal`PartitionRagged[
#
, Append[
ConstantArray[len, Quotient[Length@#, len]]
, Mod[Length@#, len]
]
] &@Flatten[lst][[len + 1 ;;]]
] &
, {}
, inlist]
] //. {} :> (##[]&)
Usage:
partitionByLength[inlist, 10]
(* (* {{{"a", "b", "c", "d", "e"}, {" "}, {"f", "g", "h"}}, {{"i", "j", "k", "l"}, {"m", "n", "o", "p"}}} *)
lst = {Range[6], Range[10], Range[2]}
partitionByLength[lst, 4]
(* {{{1, 2, 3, 4}}, {{5, 6}, {1, 2}}, {{3, 4, 5, 6}}, {{7, 8, 9, 10}}, {{1, 2}}} *)
Original post
Here's something that seems to work. It's not well tested (perhaps you can add some other examples?) and it's probably slow, but here goes:
partition10[inlist_] := First@Last@Reap@Fold[
If[
Tr[Length /@ (lst = Append[#1, #2])] <= 10
, lst
, Sow[#1]; {#2}
] &
, {}
, Append[inlist, Range[11]]
]
inlist = {{"a", "b", "c", "d", "e"}, {" "}, {"f", "g", "h"}, {"i", "j", "k", "l"}, {"m", "n", "o", "p"}};
partition10[inlist]
(* {{{"a", "b", "c", "d", "e"}, {" "}, {"f", "g", "h"}}, {{"i", "j", "k", "l"}, {"m", "n", "o", "p"}}} *)
For the lists that have sublists of length greater than 10, my method requires pre-processing of the list, and so I cannot treat that case until I know how theses sublists of length greater than 10 can be treated (see my comment on the original post).
Flatten@result==Flatten@source
to be true? $\endgroup$n
elements? Or can you capture some of the first elements of the list if the previous lists don't yet add up to length 10? $\endgroup$