组合部分和

use*_*503 4 numbers r combinatorics

我正在寻找R一个函数partial.sum(),它接受一个数字向量并返回所有部分和的升序排序向量:

test=c(2,5,10)
partial.sum(test)

# 2 5 7 10 12 15 17
## 2 is the sum of element 2
## 5 is the sum of element 5    
## 7 is the sum of elements 2 & 5    
## 10 is the sum of element 10    
## 12 is the sum of elements 2 & 10    
## 15 is the sum of elements 5 & 10
## 17 is the sum of elements 2 & 5 & 10
Run Code Online (Sandbox Code Playgroud)

flo*_*del 6

这是一个使用递归.(不要声称它有效率)

partial.sum <- function(x) {
   slave <- function(x) {
      if (length(x)) {
         y <- Recall(x[-1])
         c(y + 0, y + x[1])
      } else 0
   }
   sort(unique(slave(x)[-1]))
}

partial.sum(c(2,5,10))
# [1]  2  5  7 10 12 15 17
Run Code Online (Sandbox Code Playgroud)

编辑:好吧,事实证明它比我想象的要快一点:

x <- 1:20
microbenchmark(flodel(x), dason(x), matthew(x), times = 10)
# Unit: milliseconds
#        expr        min        lq     median        uq       max neval
#   flodel(x)   86.31128   86.9966   94.12023  125.1013  163.5824    10
#    dason(x) 2407.27062 2461.2022 2633.73003 2846.2639 3031.7250    10
#  matthew(x) 3084.59227 3191.7810 3304.36064 3693.8595 3883.2767    10
Run Code Online (Sandbox Code Playgroud)

(我在适当的时候添加了sort和/或uniquedason和matthew的功能以进行公平比较.)