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

前端 未结 5 1233
青春惊慌失措
青春惊慌失措 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:12

    For the combinations, do you want this:

    combinations <- lapply(seq_along(weights), function(x) combn(weights, x))
    

    Then for the sums:

    sums <- lapply(combinations, colSums)
    inds <- lapply(sums, function(x) which(x == 1))
    lapply(seq_along(inds), function(x) combinations[[x]][, inds[[x]]])
    

提交回复
热议问题