I'm using Mathematica 7 and with a combinatorica package function I can get all combinations of a certain number from a list of elements where the order doesn't matter and there is no repetition.e.g:
in: KSubsets[{a, b, c, d}, 3]
out: {{a, b, c}, {a, b, d}, {a, c, d}, {b, c, d}}
I cannot find a function that will give me all combinations of a certain number from a list of elements where the order doesn't matter and there is repetition. i.e. the above example would include elements like {a,a,b},{a,a,a},{b,b,b}...etc in the output.
It may require a custom function. If I can come up with one I will post an answer but for now I don't see an obvious solution.
Edit: Ideally the output will not contain duplication of a combination e.g. Tuples[{a, b, c, d}, 3] will return a list that contains two elements like {a,a,b} and {b,a,a} which from a combinations point of view are the same.
Here's a simple solution that takes advantage of Mathetmatica's built-in function Subsets and thus is a nice balance between simplicity and performance. There is a simple bijection between k-subsets of [n+k-1] and k-combinations of [n] with repetition. This function changes subsets into combinations with repetition.
So
yields
You can encode each combination as
{na,nb,nc,nd}
where na gives the number of timesa
appears. The task is then to find all possible combinations of 4 non-negative integers that add up to 3.IntegerPartition
gives a fast way to generate all such such combinations where order doesn't matter, and you follow it withPermutations
to account for different ordersJust for fun, here's timing comparison between IntegerPartitions and Tuples for this task, in log-seconds
http://yaroslavvb.com/upload/save/tuples-vs-partitions.png
A slight variant on the elegant method given by High Performance Mark:
Permutations is slightly more versatile (but not what you are looking for?)
For example:
gives the following
Edit:
is probably better
Edit-2
Of course, Cases may also be used. For example
Edit-3.
The two approaches will differ if the list contains a repeated element. The output from the following (approach 2), for example, will contain duplicates (which may or may not be desired):
They may easily be got rid of:
The following evaluates to 'True' (remove duplicate elements from the list presented to approach 2, and Sort the list produced by approach 1 (High Performance Mark method):
as does the following (remove duplicates from output of approach 2, Sort output of approach 1):
Sorry about that!