Suppose that I have a 1-D list called myList
. Here's an example:
myList = {"A", "B", "C", "D"};
I want to write (or find built-in) a function called getConfigurations
that will return all possible "n choose k" lists. Before I explain what I mean by an "n choose k" list, let me just write down the result I would like to obtain from getConfigurations
for the list myList
given above:
getConfigurations[myList]
{ (* configurations when ONE element is chosen: k=1 *) {{"A"}, {"B"}, {"C"}, {"D"}}, (* configurations when TWO elements are chosen: k=2 *) {{"A", "B"}, {"A", "C"}, {"A", "D"}, {"B", "C"}, {"B", "D"}, {"C", "D"}}, (* configurations when THREE elements are chosen: k=3 *) {{"A", "B", "C"}, {"A", "B", "D"}, {"A", "C", "D"}, {"B", "C", "D"}}, (* configurations when FOUR elements are chosen: k=4 *) {{"A", "B", "C", "D"}} }
I am not sure what (if anything) this is called in combinatorics, but it reminds me of the binomial coefficient:
$${n \choose k} = \frac{n!}{k! (n-k)!}$$
which I remember being called the "n choose k" binomial coefficient.
In the example myList
given above, $n = 4$ because Length[myList]
is 4. For each value of k ($k = 1, 2, 3, 4$), I want to generate all possible configurations. In my case, order does not matter, so for example, {"B", "A"}
is indistinguishable from {"A", "B"}
.
I think that the formula for $n \choose k$ gives the number of configurations. It turns out that
$${4 \choose 1} = 4$$ $${4 \choose 2} = 6$$ $${4 \choose 3} = 4$$ $${4 \choose 4} = 1$$
which can be seen from Table[Binomial[4, k], {k, 1, 4}]
.
However, I don't just want the number of possible configurations for each k; instead, I want to actually generate the configurations themselves. Is there a simple and elegant -- or perhaps even built-in -- way to do this?
Subsets[myList, {k}]
$\endgroup$ – ciao Apr 27 '14 at 21:54