5

I would like to generate a list of all the possible combinations of two lists. As for instance, given L=3;

list={0,1,2};

I would like to obtain the list {{0,0,0},{0,0,1},{0,0,2},{0,1,0},{0,2,0},{1,0,0},{2,0,0}}

I did it with the code:

f[d_, L_] := Module[{l, st},
   l = Join[{d}, Table[0, {j, L - 1}]];
   st = {};
   AppendTo[st, Permutations@l];
   Return[First@st];
   ];

d = 2;
L = 3;
Flatten[Join[Table[f[j, L], {j, 0, d}]], 1]

Is there a better way to do by combining lists?

Mr.Wizard
  • 271,378
  • 34
  • 587
  • 1,371
Galuoises
  • 523
  • 2
  • 8

3 Answers3

5
list = {0, 1, 2};
list2 = {0, 0};
Sort[Join @@ (Permutations[Join[list2, {#}]] & /@ list)]

{{0, 0, 0}, {0, 0, 1}, {0, 0, 2}, {0, 1, 0}, {0, 2, 0}, {1, 0, 0}, {2, 0, 0}}

kglr
  • 394,356
  • 18
  • 477
  • 896
3

Starting over I just realized that for the example given we can do this simply with KroneckerProduct:

f2[d_, L_] := 
  Range[d] ~KroneckerProduct~ IdentityMatrix[L] // Prepend[#, 0*First@#] &

f2[2, 3]

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

f2[86, 99] // Length // RepeatedTiming

(* {0.00445, 8515} *)

If you will accept your output in the form of a SparseArray this can be made more than an order of magnitude faster:

f3[d_, L_] := 
  Range[d] ~KroneckerProduct~ IdentityMatrix[L, SparseArray] // Prepend[#, 0*First@#] &

f3[86, 99] // Length // RepeatedTiming

(* {0.000288, 8515} *)

Compare the performance of kglr's method, e.g.:

fx[d_, L_] :=
 With[{list = Range[0, d], list2 = ConstantArray[0, L - 1]}, 
  Sort[Join @@ (Permutations[Join[list2, {#}]] & /@ list)]
  ]

fx[86, 99] // Length // RepeatedTiming

(* {0.05107, 8515} *)

Mr.Wizard
  • 271,378
  • 34
  • 587
  • 1,371
  • Thank you so much...it works perfectly! – Galuoises Jul 03 '17 at 14:06
  • I changed the Prepend part to // Prepend[ConstantArray[0, {L}]]...it seems it goes just a bit faster – Galuoises Jul 03 '17 at 14:15
  • @Galuoises You're welcome. By the way if order matters and you want a different one try KroneckerProduct[IdentityMatrix[L], Range[d]]\[Transpose] // Prepend[#, ConstantArray[0, L]] & – Mr.Wizard Jul 03 '17 at 14:46
0
Permutations[{0, 0, #}, {3}] & /@ Range[0, 2] // Flatten[#, 1] &

Original Answer

Permutations /@ IntegerDigits[Range[0, 2], 2 + 1, 3] // Join @@ # &

{{0, 0, 0}, {0, 0, 1}, {0, 1, 0}, {1, 0, 0}, {0, 0, 2}, {0, 2, 0}, {2, 0, 0}}

user1066
  • 17,923
  • 3
  • 31
  • 49