15

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}
m_goldberg
  • 107,779
  • 16
  • 103
  • 257
Filippo Vitale
  • 253
  • 3
  • 7

3 Answers3

19
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}
*)
m_goldberg
  • 107,779
  • 16
  • 103
  • 257
Dr. belisarius
  • 115,881
  • 13
  • 203
  • 453
8
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}} *)
m_goldberg
  • 107,779
  • 16
  • 103
  • 257
chyanog
  • 15,542
  • 3
  • 40
  • 78
1
(* 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 &]
Ali Hashmi
  • 8,950
  • 4
  • 22
  • 42