float 子集和问题的递归函数

标签 r precision subset-sum

我做了一个递归函数f(s,x)对于 subset sum problem ,当从值集合 x 中选取元素时,它能够生成总和为目标总和 's' 的所有唯一组合。 .

例如,假设 x <- c(2,4,8,10) ,和s <- 10表示目标总和,函数为f下面

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(s-k, x[x<= s-k], min(k,head(x[x<=s-k],1)), c(r,k))),recursive = F)) 
  }
}

我可以获得子集和的所有组合,即

> 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

上面的函数适用于整数 xs但是,当我缩小两者时 xs乘以 10,即 x 的 float 和s ,那么输出就变成了不需要的:

> 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在处理 float 时,但经过多次尝试未能修复。任何人都可以帮助我解决这个问题而不需要对函数进行大的更改f

提前感谢任何帮助!

最佳答案

您可以在减法中使用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)

返回所需的输出:

[[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

关于 float 子集和问题的递归函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58747069/

相关文章:

algorithm - 包含 2675 个数字的列表的子集总和

r - 最大样本

math - float 学有问题吗?

java - 对双数取模

java - 递归方法未正确执行

prolog - (Prolog) 检查一个列表是否可以分成两个总和相等的子列表

r - 带有 ggplot2 的标准 eval 没有 `aes_string()`

r bquote : remove the space before approximately equal plotmath symbol

MySQL:如何填充表以用现有数据填充缺失的行

python - BBP 算法所需的工作精度?