R 浮点数子集和问题的递归函数
我为的创建了一个递归函数R 浮点数子集和问题的递归函数,r,precision,subset-sum,R,Precision,Subset Sum,我为的创建了一个递归函数f(s,x),当从值集x中拾取元素时,该函数能够生成所有唯一的组合,这些组合的总和为目标和 例如,假设x可以在减法中使用round,并设置小数点 f <- function(s, x, xhead = head(x,1), r = c()) { if (s == 0) { return(list(r)) } else { x <- sort(x,decreasing = T) return(unlist(lapply(x[x&l
f(s,x)
,当从值集x
中拾取元素时,该函数能够生成所有唯一的组合,这些组合的总和为目标和
例如,假设
x可以在减法中使用round
,并设置小数点
f <- function(s, x, xhead = head(x,1), r = c()) {
if (s == 0) {
return(list(r))
} else {
x <- sort(x,decreasing = T)
return(unlist(lapply(x[x<=min(xhead,s)], function(k) f(round(s-k, 4), x[x<= round(s-k, 4)], min(k,head(x[x<= round(s-k, 4)],1)), c(r,k))),recursive = F))
}
}
f(s/10,x/10)
谢谢!所以使用round
来消除减法过程中的不精确性?那么我想它应该取决于x
> f(s,x)
[[1]]
[1] 10
[[2]]
[1] 8 2
[[3]]
[1] 4 4 2
[[4]]
[1] 4 2 2 2
[[5]]
[1] 2 2 2 2 2
> f(s/10,x/10)
[[1]]
[1] 1
> Map(function(v) v/10, f(s,x))
[[1]]
[1] 1
[[2]]
[1] 0.8 0.2
[[3]]
[1] 0.4 0.4 0.2
[[4]]
[1] 0.4 0.2 0.2 0.2
[[5]]
[1] 0.2 0.2 0.2 0.2 0.2
f <- function(s, x, xhead = head(x,1), r = c()) {
if (s == 0) {
return(list(r))
} else {
x <- sort(x,decreasing = T)
return(unlist(lapply(x[x<=min(xhead,s)], function(k) f(round(s-k, 4), x[x<= round(s-k, 4)], min(k,head(x[x<= round(s-k, 4)],1)), c(r,k))),recursive = F))
}
}
f(s/10,x/10)
[[1]]
[1] 1
[[2]]
[1] 0.8 0.2
[[3]]
[1] 0.4 0.4 0.2
[[4]]
[1] 0.4 0.2 0.2 0.2
[[5]]
[1] 0.2 0.2 0.2 0.2 0.2