All possible combinations of a set that sum to a target value

前端 未结 5 1224
青春惊慌失措
青春惊慌失措 2020-12-01 17:21

I have an input vector such as:

weights <- seq(0, 1, by = 0.2)

I would like to generate all the combinations of weights (repeats allowed

5条回答
  •  抹茶落季
    2020-12-01 18:15

    If you are planning to implement it using base R only, then an alternative approach is the recursion.

    Assuming x <- c(1,2,4,8), and s <- 9 denotes the target sum, then the following function can get you there:

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

    which f(s,x) gives:

    [[1]]
    [1] 8 1
    
    [[2]]
    [1] 4 4 1
    
    [[3]]
    [1] 4 2 2 1
    
    [[4]]
    [1] 4 2 1 1 1
    
    [[5]]
    [1] 4 1 1 1 1 1
    
    [[6]]
    [1] 2 2 2 2 1
    
    [[7]]
    [1] 2 2 2 1 1 1
    
    [[8]]
    [1] 2 2 1 1 1 1 1
    
    [[9]]
    [1] 2 1 1 1 1 1 1 1
    
    [[10]]
    [1] 1 1 1 1 1 1 1 1 1
    

    Note: round(*,digits=10) is used to take care of floating-point numbers, where digits should adapt to decimals of input.

提交回复
热议问题