List of tuples without duplicates & repeated values
The accepted answer will quickly blow up with arguments of more than trivial sizes.
For example, with vals = {10, 20, 5, a, b, c}
and n=10
, it takes nearly two minutes to finish on my laptop, generating only 3003 results.
Better to generate the results directly, as a simple nested iteration:
f2[vals_, n_] :=
With[{i = {#2, #1, Length@vals} & @@@
Partition[Prepend[Array[i, n], 1], 2, 1]},
Partition[vals[[Flatten[Table @@ {i[[All, 1]], Sequence @@ i}]]], n]];
This takes a few hundredths of a second to generate the same results from the aforementioned example.
It will also handle cases where the current answer will simply crash out with a "insufficient memory available" error (say 20 values and length 10).
n = 2;
vals = {0, 1};
Tuples[vals, {n}] // DeleteDuplicatesBy[#, Sort] &
As the comment said
Tuples[vals, {n}] // DeleteDuplicatesBy[Sort]
Also works, more clear.
Some explanations:
The key is: you "sort" the list to see whether they are duplicate.
So I use Sort
to be DeleteDuplicatesBy
's condition.