# Generate a list of values with equal number of each value

I want to create a list of 32 values such that from {a,b} I can generate

{{a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b},
{a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,b,a,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b},...,
{b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a}}


(that's exactly 16 a's and 16 b's in each array, with repeats allowed).

I have tried Select[Tuples[{a,b},32],Count[##,a]==16], but get an error that "The length of the output of Tuples[{a,b},32] should be a machine integer." The problem as I see it is that Tuples is generating a lot of unneeded cases for my problem and the computer can't handle such a large number (and it would take a really long time even if it could). I did a study of the timing of running some lower length arrays and assuming that the scaling stays linear (like it did for some of the larger numbers) it would take nearly 7 hours.

EDIT: I have the answer, but it won't let me post it, because I am new. So here it goes:

Building off of Kuba's suggestion, I came up with an answer that works for my problem. Sorry if I was unclear. I built a list and then made every permutation of the list until all elements were switched. It is easy enough to make sure it goes through the switch and then back to the original (thus generating every possible combination without eliminating repeats).

list = Join @@ (ConstantArray[#, 16] & /@ {a, b});
For[c = 1, c < 17, c++,
For[d = 17, d <= 33 - c, d++,
new = Permute[list, Cycles[{{c, d}}]];
];
list = new
];


Hopefully this will help someone else!

• Which version of Mathematica do you have? Only in version 9 were machine integers changed to 64-bit (in the 64-bit version only, of course). If you have version 8 or below then $32 \times 2^{32}$ clearly is larger than a (32-bit) machine integer. – Oleksandr R. Apr 17 '14 at 17:44
• @OleksandrR. I'm a little bit confused, could you point out where I've said something stupid? :) – Kuba Apr 17 '14 at 18:05
• @Kuba I think that what you've said is all okay. It is not obvious that, until recently, a machine integer in a 64-bit version of Mathematica was still only 32 bits. Your comments about memory consumption are accurate, but the reason that Mathematica $\leq$ 8 cannot form the unfiltered list of tuples is not memory but rather addressability of the resulting array. – Oleksandr R. Apr 17 '14 at 18:17
• Your list will have binomial(32,16) elephants. That's a lot of pachyderm to be packing. – Daniel Lichtblau Apr 17 '14 at 18:48

It is not a problem of your method. You need a set of lenght: 32!/(16!)^2 == 601 080 390 where each entry is list with those 32 elements. So at the end 19 234 572 480 elements in the array. Too many, at least for my pc.
Join @@ (ConstantArray[#, 3] & /@ {a, b}) // Permutations

• your formula is right but not the number: 32 (32!/(16!)^2) == 19234572480 (off by 1/2 .. ) – george2079 Apr 17 '14 at 21:45