# Generating a list of all possible combinations satisfying a constraint

Defining

\Psi=A_n1.B_n2.C_n3.D_n4.E_n5.F_n6


where the dot means some kind of product that I need to use in my full code. How do I generate a list of all possible terms like the above where n1, n2, n3, n4, n5, n6 can only be -1,0,1 and are constrained by n1+n2+n3+n4+n5+n6=3?

For example, the list would have a term of the form

list1={..., A_0.B_0.C_0.D_1.E_1.F_1,...}


Edit: I also need that each term in the list comes multiplied with an arbitrary coefficient numbered by the position of the term in the list. So if the above example denotes the 15th term, the list I want would be

list1={...,a_15 A_0.B_0.C_0.D_1.E_1.F_1,...}


where a_15 is an arbitrary coefficient.

To avoid conflicts with built-in Mathematica symbols, do not use capital letters for user-defined symbols. For example, C, D, and E have predefined meanings. I have used {a, b, c, d, e, f} and k for the arbitrary coefficients.

ClearAll["Global*"];

(Format[#[n_]] := Subscript[#, n]) & /@
{a, b, c, d, e, f, k};

indices = Select[Tuples[{-1, 0, 1}, 6], Total[#] == 3 &];

n = Length[indices]

(* 50 *)

list1 = MapIndexed[
k[#2[[1]]]*
CenterDot @@ #1 &, ((Transpose[{{a, b, c, d, e, f}, #}] & /@
indices) /. {sym_Symbol, i_} :> sym[i])];

Length[list1]

(* 50 *)


The first few terms of list1 are

list1[[1 ;; 6]]


You need to define the operation for CenterDot. By default, the coefficients k display after the CenterDot products.

An alternative way to get the index list (all possible 6-tuples of {-1, 0, 1} that add up to 3) is to use IntegerPartitions with {-1, 0, 1} as the third argument and take permutations of each partition:

ip = Join @@ (Permutations /@ IntegerPartitions[3, {6}, {-1, 0, 1}]);


This approach is faster than using Tuples and filtering the results. When sorted, ip and Bob Hanlon's indices are the same:

Sort @ ip == Sort @ indices


True

First, use Bob Hanlon's suggestion to use Subscript for formatting indexed variables:

ClearAll[a, b, c, d, e, f, k]

vars = {a, b, c, d, e, f, k};

(Format[#[n_]] := Subscript[#, n]) & /@ vars;


To get the lists of indexed variables use a combination of Inner + CenterDot and multiply it with Array[k, Length @ ip]:

l1 = Array[k, Length @ ip] Map[Inner[# @ #2 &, Most @ vars, #, CenterDot] &] @ ip;

Length @ l1

50

l1 // Short[#, 3] &


• If I try to apply a function in l1, Mathematica does nothing. But if I copy the output of l1 and then apply the function in this copied output, Mathematica recognizes and does what I expect. Do you know what is happening? Jan 15 at 22:11
• Also, I then ask if l1=== copied output` and the answer is False. I have no idea what is happening, I Quit all cells and the problem still persists. Jan 15 at 22:15