简体   繁体   中英

recursive function for subset sum problem with floating-point numbers

I made a recursion function f(s,x) for the subset sum problem , which is able to produce all unique combinations that sum up to the target sum 's' when picking elements from the set of values x .

For example, assuming x <- c(2,4,8,10) , and s <- 10 denotes the target sum, with the function f below

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)) 
  }
}

I can get all combinations for subset sum, ie,

> 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

The function above works well with integers for x and s . However , when I scaled down both x and s by 10, ie, floating-point numbers for x and s , then the output becomes the undesired ones:

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

but the desired output should be like

> 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

I suspect there must be some wring for my function f when dealing with floating-point numbers, but failed to fix it after several trials. Can anyone help me address this issue without big changes for the function f ?

Appreciate any help in advance!

You can use round in your subtraction and set the decimal points

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)

Which returns the desired 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM