15
$\begingroup$

How can I find all the permutations of {a, b, c} where a + b + c = n?

For instance: if n = 3 the permutations I seel are:

  • Permutations[{3, 0, 0}]
  • Permutations[{2, 1, 0}]
  • {1, 1, 1}
$\endgroup$
2
  • $\begingroup$ Related: (19486) $\endgroup$
    – Mr.Wizard
    Commented Mar 11, 2013 at 6:03
  • $\begingroup$ good find @Mr.Wizard ! I searched for ages permutations-related questions but not IntegerPartitions... $\endgroup$ Commented Mar 11, 2013 at 6:49

3 Answers 3

19
$\begingroup$
f[sum_, quant_] :=
  Flatten[Permutations /@ IntegerPartitions[sum, {quant}, Range[0, sum]], 1]

f[3, 3] // Column
(*
{3,0,0}
{0,3,0}
{0,0,3}
{2,1,0}
{2,0,1}
{1,2,0}
{1,0,2}
{0,2,1}
{0,1,2}
{1,1,1}
*)

f[4, 2] // Column
(*
{4,0}
{0,4}
{3,1}
{1,3}
{2,2}
*)
$\endgroup$
8
$\begingroup$
f[sum_, quant_] := FrobeniusSolve[Array[1 &, quant], sum]

f[3, 3]

(*
    {{0, 0, 3}, {0, 1, 2}, {0, 2, 1}, {0, 3, 0}, {1, 0, 2}, {1, 1, 1},
    {1, 2, 0}, {2, 0, 1}, {2, 1, 0}, {3, 0, 0}}
*)

f[4, 2]

(* {{0, 4}, {1, 3}, {2, 2}, {3, 1}, {4, 0}} *)
$\endgroup$
1
  • 1
    $\begingroup$ For readibility purpose, may I suggest: ConstantArray[1, quant] instead of Array[1 &, quant] ? $\endgroup$ Commented Mar 11, 2013 at 8:49
1
$\begingroup$
(* a crude way: lets assume we wish to find all the permutations of a list of three integers that add up to 4 *)

Select[Permutations[Flatten@ConstantArray[Range[0, 4], 3], {3}], 
Plus @@ # == 4 &]
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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