2
$\begingroup$

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}}
$\endgroup$
  • 1
    $\begingroup$ For the first one and if the order is not important: Flatten[Permutations /@ IntegerPartitions[4, {2}], 1] $\endgroup$ – Algohi Feb 9 '15 at 1:53
3
$\begingroup$
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}}}

$\endgroup$
  • 1
    $\begingroup$ One can use FrobeniusSolve[] instead: f[n_Integer, m_Integer] := Select[FrobeniusSolve[ConstantArray[1, m], n], FreeQ[0]] $\endgroup$ – J. M. is away Dec 11 '16 at 5:36
0
$\begingroup$

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}}]
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.