Let's say I have a list:
{a, b, c}
I would like to, for say $n=2$ get every distinct pair from that list. That is, the expected result should be, for some function choose
:
choose[{a, b, c}, 2]
(* {{a, b}, {a, c}, {b, c}} *)
My attempt at this was like so:
choose[list_, n_] :=
DeleteDuplicates[Permutations[list, {n}], Union[#1, #2] == #1 &]
And it does give the expected result for this example. There are, however, some problems in which I would like some help addressing:
Permutations
creates more combinations that I need, which forces me to useDeleteDuplicates
. Is there away to directly arrive at all combinations?- The
DeleteDuplicates
operation is very costly. Is there a way I could use the structure of thePermutations
result to my advantage to get rid of the unwanted repeats? - My function DOES make an error when there are supposed to be intended repeats. For instance,
choose[{b, b, c}, 2]
should give{{b,b}, {b, c}, {c, b}}
- as every element in the list is considered "distinct" even though the values could be equal - but instead, the duplicate deletion removes the{c, b}
.
EDIT
I have figured out a way to address #3. If I create a symbolic list tempList
in which every element is unique, then replace that with the list, I am able to preserve "distinct" combinations even though they have the same value:
choose[list_, n_] :=
With[{tempList = Array[Unique[] &, Length@list]},
DeleteDuplicates[
Permutations[tempList, {n}],
Union[#1, #2] == #1 &] /. Thread[tempList -> list]]
However, there's still room for improvement as having to use the replacement is not great for larger list
lengths and values of $n$.