Julia:具有替换的 n 个元素的唯一集合

Jul*_*ian 3 combinatorics julia

给定一个向量v = [1,..,n],我尝试计算所有唯一的 n 元素集并在 julia 中进行替换。

由于我想对较大的 n 值执行此操作,因此我正在寻找一种有效的解决方案,可能使用迭代器。

例如,让我们考虑v = [1, 2, 3]:这应该导致[1,1,1], [1,1,2], [1,1,3], [1,2,2], [1,2,3], [1,3,3], [2,2,2], [2,2,3], [2,3,3], [3,3,3]. 对于唯一,我的意思是如果[1,1,2]是一个解决方案,那么它的任何排列[1,2,1], [2,1,1]都不是。

我当前的解决方案基于partitions函数,但不允许我限制元素 [1,..,n] 的计算

for i in n:n^2
  for j in partitions(i, n)
    ## ignore sets which exceed the range [1,n]
    if maximum(j) <= n
      ## accept as solution
    end
  end
end
Run Code Online (Sandbox Code Playgroud)

Ran*_*Lai 5

In julia v0.5.0, combinatorics.jl has a with_replacement_combinations method.

julia> collect(with_replacement_combinations(1:4,3))
20-element Array{Array{Int64,1},1}:
 [1,1,1]
 [1,1,2]
 [1,1,3]
 [1,1,4]
 [1,2,2]
 [1,2,3]
 [1,2,4]
 [1,3,3]
 [1,3,4]
 [1,4,4]
 [2,2,2]
 [2,2,3]
 [2,2,4]
 [2,3,3]
 [2,3,4]
 [2,4,4]
 [3,3,3]
 [3,3,4]
 [3,4,4]
 [4,4,4]
Run Code Online (Sandbox Code Playgroud)