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
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
...