Mathematica Stack Exchange is a question and answer site for users of Mathematica. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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}
share|improve this question
    
Related: (19486) – Mr.Wizard Mar 11 '13 at 6:03
    
good find @Mr.Wizard ! I searched for ages permutations-related questions but not IntegerPartitions... – Filippo Vitale Mar 11 '13 at 6:49
up vote 13 down vote accepted
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}
*)
share|improve this answer
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}} *)
share|improve this answer
    
For readibility purpose, may I suggest: ConstantArray[1, quant] instead of Array[1 &, quant] ? – Filippo Vitale Mar 11 '13 at 8:49
    
Of course. And ConstantArray more faster, try ConstantArray[1, 10^7]; // Timing, Array[1 &, 10^7]; // Timing – chyaong Mar 11 '13 at 9:28

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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