给定一个向量 v = [1,..,n]
,我尝试在 julia 中计算所有具有替换的 n 个元素的唯一集合。
由于我想对较大的 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
最佳答案
我想,它不会比一行更短(使用迭代器)。
using IterTools
import Combinatorics.combinations
n=3
collect(imap(c -> Int[c[k]-k+1 for k=1:length(c)],combinations(1:(2n-1),n)))
关于combinatorics - Julia:带有替换的唯一 n 个元素集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26313868/