4
$\begingroup$

I have to write a function that takes two arguments: a list list and an integer n. The function should return another list called result with sublists of length n. These sublists should contain all variations of elements from list, with no duplicates. Could someone help me how to approach this problem? Thanks in advance!

$\endgroup$
1
  • 1
    $\begingroup$ Does Subsets[list, {n}] do what you need? $\endgroup$
    – Carl Woll
    Mar 4 at 19:14
4
$\begingroup$

You have a list of numbers without duplicates. You want to create all sublists with given length, where the order matters and no duplicates in the sublist are allowed, for short: variations without repetition.

For safety, we first make sure that the original list contains no duplicates. Then we create all sublists with length n. Finally we create all permutations of the sublists:

variations[list_, n_] := Module[{d = Union[list]},
  d = Subsets[d, {n}];
  Flatten[Permutations /@ d, 1]
]

Here is a small test:

dat = Range[5];
variations[dat, 3]

enter image description here

$\endgroup$
1
  • $\begingroup$ thanks a ton, works perfectly fine! $\endgroup$
    – noob3000
    Mar 4 at 20:20
3
$\begingroup$

You can use Permutations directly using the second argument to specify the length of sublists:

ClearAll[duplicateFreePermutations]

duplicateFreePermutations[lst_, n_] := Permutations[Union @ lst, {n}]

Examples:

duplicateFreePermutations[Range[5], 3]

enter image description here

duplicateFreePermutations[{a, b, b, c, c}, 3]
{{a, b, c}, {a, c, b}, {b, a, c}, {b, c, a}, {c, a, b}, {c, b, a}}
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.