all combinations of k numbers between 0 and n whose sum equals n, speed optimization

后端 未结 5 1948
Happy的楠姐
Happy的楠姐 2021-01-25 18:42

I have this R function to generate a matrix of all combinations of k numbers between 0 and n whose sum equals n. This is one of the bottlenecks of my program as it becomes extre

5条回答
  •  谎友^
    谎友^ (楼主)
    2021-01-25 19:16

    It is hard to tell if it will be useful unless you answer my question regarding your typical values for n and k (please do.) Here is a version using recursion that seems to be faster than josilber's using his benchmark test:

    sum.comb3 <- function(n, k) {
    
       stopifnot(k > 0L)
    
       REC <- function(n, k) {
          if (k == 1L) list(n) else
          unlist(lapply(0:n, function(i)Map(c, i, REC(n - i, k - 1L))),
                 recursive = FALSE)
       }
    
       matrix(unlist(REC(n, k)), ncol = k, byrow = TRUE)
    }
    
    microbenchmark(sum.comb(3, 10), sum.comb2(3, 10), sum.comb3(3, 10))
    # Unit: milliseconds
    #              expr      min       lq   median       uq      max neval
    #  sum.comb2(3, 10) 39.55612 40.60798 41.91954 44.26756 70.44944   100
    #  sum.comb3(3, 10) 25.86008 27.74415 28.37080 29.65567 34.18620   100
    

提交回复
热议问题