# Is there a way to split a list (or number) into a specific number of parts?

I know there's a way to split a list into parts of a specific length, and I know there's a way to get all possible partitions of an integer. But I was wondering if there's a way to partition a list into, say, three parts. Kind of like the balls and dividers method, except that it actually returns the number of balls between each set of dividers. So if I put in something like:

f[4,2] or f[{1,1,1,1},2]

it will return

{2,2},{1,3},{3,1} or {{1,1},{1,1}},{{1},{1,1,1}},{{1,1,1},{1}}
• For the first one and if the order is not important: Flatten[Permutations /@ IntegerPartitions[4, {2}], 1] Commented Feb 9, 2015 at 1:53

ClearAll[f];
f[n_Integer, m_Integer] := DeleteDuplicates[Join@@Permutations/@IntegerPartitions[n, {m}]]
f[x_List, m_Integer] :=  Module[{n=Length@x}, Internal`PartitionRagged[x, #] & /@ f[n, m]]

Examples:

f[4, 2]

{{3, 1}, {2, 2}, {1, 3}}

f[{1, 1, 1, 1}, 2]

{{{1, 1, 1}, {1}},
{{1, 1}, {1, 1}},
{{1}, {1, 1, 1}}}

f[5, 3]

{{3, 1, 1}, {1, 3, 1}, {1, 1, 3}, {2, 2, 1}, {2, 1, 2}, {1, 2, 2}}

f[Range@5, 3]

{{{1, 2, 3}, {4}, {5}},
{{1}, {2, 3, 4}, {5}},
{{1}, {2}, {3, 4, 5}},
{{1, 2}, {3, 4}, {5}},
{{1, 2}, {3}, {4, 5}},
{{1}, {2, 3}, {4, 5}}}

• One can use FrobeniusSolve[] instead: f[n_Integer, m_Integer] := Select[FrobeniusSolve[ConstantArray[1, m], n], FreeQ[0]] Commented Dec 11, 2016 at 5:36

For partitioning a list, you can use the Basic Example from the Help page for ReplaceList. For example,

ReplaceList[{1, 1, 1, 1}, {x__, y__} -> {{x}, {y}}]

or

ReplaceList[Range[5], {x__, y__, z__} -> {{x}, {y}, {z}}]