# How can I create a function with all permutations of all digits up to the number of permutations asked?

I wish to create all permutations of all digits from a function.

For e.g. I have the array [1,2,3].
I would like the function to first print all possible permutations of 1 digit numbers:

``````1
2
3
``````

then all possible permutations of 2-digit numbers(duplicates like 11, 22, 33 included)

``````11
12
13
21
22
23
31
32
33
``````

and similarly for the 3 digit numbers.

I want to include all sort of possible permutations(11, 111, 222 etc.) up to the number of digits in the array, like in this example, I would like to have all permutations up to 3 digits.
How can I write it?

You can use `multi_cartesian_product()` from the `itertools` crate:

``````fn variations_up_to_length<T>(items: &[T]) -> impl Iterator<Item = Vec<&T>> {
(1..=items.len()).flat_map(|n| {
std::iter::repeat(items.iter()).take(n).multi_cartesian_product()
})
}
``````

By the way, these are not called permutations. These are called variations with repetition or Cartesian product or set-theoretic direct product.

2 Likes

Can I obtain such a result when the elements in the set are not integers, will it work for `char` or `& str`?
@H2CO3

Just try it, I guess? The answer is yes 1 Like

The implementation is generic.

1 Like

thanks