TransWikia.com

Function that returns disjoint sublists

Mathematica Asked by noob3000 on March 26, 2021

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!

2 Answers

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

Correct answer by Daniel Huber on March 26, 2021

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}}

Answered by kglr on March 26, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP