簡體   English   中英

用於浮點數子集和問題的遞歸 function

[英]recursive function for subset sum problem with floating-point numbers

我為子集總和問題做了一個遞歸 function f(s,x) ,當從一組值x中選擇元素時,它能夠產生所有唯一的組合,這些組合總和為目標總和 's'。

例如,假設x <- c(2,4,8,10) ,並且s <- 10表示目標總和,下面的 function 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

上面的 function 適用於xs整數。 但是,當我將x s x s ,那么 output 就變成了不想要的:

> f(s/10,x/10)
[[1]]
[1] 1

但所需的 output 應該像

> 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

我懷疑我的 function f在處理浮點數時一定有一些問題,但經過多次試驗后未能解決。 任何人都可以幫我解決這個問題,而無需對 function 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)

返回所需的 output:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM