Non-Unique sets of n elements with replacement

Given a vector v = [1,…,n], I am trying to compute all non-unique sets of k elements with replacement.

For example, v = [1, 2, 3, 4, 5] and k = 3: should result in [1,1,1], [1,1,2], [1,1,3], [1,1,4], [1,1,5], [1,2,1], [1,2,2], [1,2,3], [1,2,4], [1,2,5], [1,3,1], [1,3,2], [1,3,3]… [5,5,4], [5,5,5]. With non-unique, I mean that if [1,1,2] is a solution, any of its permutations [1,2,1], [2,1,1] are as well.

I originally wrote the following code that outputted the correct solution:

all_combinations = [[a, b, c, d, e] for a in min:max

                                                  for b in min:max

                                                  for c in min:max

                                                  for d in min:max

                                                  for e in min:max]

But I am now looking to do this for a variable number elements (n) and a variable combination size (k), [a, b, c, d, e, f, g] for example where k = 7 in this case and n=2 would yield [1,2] as a solution.

function samplewithreplacement(set, copies)
  Iterators.product(repeat([set],copies)...)
end

n = 7; k = 2;
all_combinations = collect(samplewithreplacement(1:n, k))
1 Like

Thank you!

Could you explain the significance of the “. . .”? What does this do in the ‘product’ function?

When given a list, for example [a,b,c], f([a,b,c]...) will be considered as f(a,b,c).

As Iterators.product take a vararg, rather than a list, this allows us to “splat” in the variables.

1 Like