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

后端 未结 5 1932
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:40

    What about something short like:

    comb = function(n, k) {
        all = combn(0:n, k)
        sums = colSums(all)
        all[, sums == n]
    }
    

    Then something like:

    comb(5, 3)
    

    which produces a matrix as you requested:

         [,1] [,2]
    [1,]    0    0
    [2,]    1    2
    [3,]    4    3
    

    Thanks to @josilber and the original poster for pointing out that the OP required all the permutations with repetition rather than combinations. A similar approach for the permutations would look like:

    perm = function(n, k) {
        grid = matrix(rep(0:n, k), n + 1, k)
        all = expand.grid(data.frame(grid))
        sums = rowSums(all)
        all[sums == n,]
    }
    

    Then something like:

    perm(5, 3)
    

    produces a matrix as you requested:

        X1 X2 X3
    6    5  0  0
    11   4  1  0
    16   3  2  0
    21   2  3  0
    26   1  4  0
    31   0  5  0
    ...
    

提交回复
热议问题