julia - Julia:具有唯一整数的向量的“n”项的所有可能总和,(重复)
问题描述
例如,假设我有一个唯一整数向量[1, 2, 6, 4]
(排序并不重要)。
给定 some n
,我想获得n
集合元素求和的所有可能值,包括将元素与自身求和。重要的是我得到的清单是详尽的。
例如,因为n = 1
我得到了原始集。因为n = 2
我应该得到所有其他元素的总和值 1,所有其他元素的总和为 2,等等。还需要某种内存,从某种意义上说,我必须知道我面临的总和来自原始集合的哪些条目从。
对于给定的、具体的n
,我知道如何解决问题。我想要一种简洁的方式来解决任何n
.
编辑:这个问题适用于 Julia 0.7 及更高版本...
解决方案
这是一个典型的任务,您可以在递归函数中使用字典(为了清楚起见,我正在注释类型):
function nsum!(x::Vector{Int}, n::Int, d=Dict{Int,Set{Vector{Int}}},
prefix::Vector{Int}=Int[])
if n == 1
for v in x
seq = [prefix; v]
s = sum(seq)
if haskey(d, s)
push!(d[s], sort!(seq))
else
d[s] = Set([sort!(seq)])
end
end
else
for v in x
nsum!(x, n-1, d, [prefix; v])
end
end
end
function genres(x::Vector{Int}, n::Int)
n < 1 && error("n must be positive")
d = Dict{Int, Set{Vector{Int}}}()
nsum!(x, n, d)
d
end
现在你可以使用它了,例如
julia> genres([1, 2, 4, 6], 3)
Dict{Int64,Set{Array{Int64,1}}} with 14 entries:
16 => Set(Array{Int64,1}[[4, 6, 6]])
11 => Set(Array{Int64,1}[[1, 4, 6]])
7 => Set(Array{Int64,1}[[1, 2, 4]])
9 => Set(Array{Int64,1}[[1, 4, 4], [1, 2, 6]])
10 => Set(Array{Int64,1}[[2, 4, 4], [2, 2, 6]])
8 => Set(Array{Int64,1}[[2, 2, 4], [1, 1, 6]])
6 => Set(Array{Int64,1}[[2, 2, 2], [1, 1, 4]])
4 => Set(Array{Int64,1}[[1, 1, 2]])
3 => Set(Array{Int64,1}[[1, 1, 1]])
5 => Set(Array{Int64,1}[[1, 2, 2]])
13 => Set(Array{Int64,1}[[1, 6, 6]])
14 => Set(Array{Int64,1}[[4, 4, 6], [2, 6, 6]])
12 => Set(Array{Int64,1}[[4, 4, 4], [2, 4, 6]])
18 => Set(Array{Int64,1}[[6, 6, 6]])
编辑:在我使用的代码中sort!
,Set
为了避免重复条目(如果你想要重复,请删除它们)。您还可以跟踪x
您在外部递归调用中达到的循环中向量索引的距离,以避免产生重复,这将加快过程。
推荐阅读
- teamcity - TeamCity 构建失败
- linux - TCP connect error during parallel execution
- php - Secondary menu not showing up in wordpress footer
- android - BaseActivity mvvm架构android,viewmodel未初始化
- c# - 表为空时获取最大日期并返回默认日期
- nginx - 在 Nginx 中将子站点添加到父站点的路径
- checkbox - 默认情况下如何使所有复选框“选中”
- php - zend Academic2 通知 ObjectHydrator
- java - 将字符串问题与 gson 解析的 JSON 数据进行比较
- mysql - MySQL表按最新日期从关系表中的值排序