Getting all combinations which sum up to 100 using R
followed by Stéphane Laurent's answer, I am able to get a super fast solution by using the uniqueperm2
function here.
library(partitions)
C = t(restrictedparts(10,8))
do.call(rbind, lapply(1:nrow(C),function(i)uniqueperm2(C[i,])))
Update, there is faster solution using iterpc
the package.
library(partitions)
library(iterpc)
C = t(restrictedparts(10,8))
do.call(rbind, lapply(1:nrow(C),function(i) getall(iterpc(table(C[i,]), order=T))))
It is about twice the speed of the uniqueperm2
> f <- function(){
do.call(rbind, lapply(1:nrow(C),function(i)uniqueperm2(C[i,])))
}
> g <- function(){
do.call(rbind, lapply(1:nrow(C),function(i) getall(iterpc(table(C[i,]), order=T))))
}
> microbenchmark(f(),g())
Unit: milliseconds
expr min lq mean median uq max neval cld
f() 36.37215 38.04941 40.43063 40.07220 42.29389 46.92574 100 b
g() 16.77462 17.45665 19.46206 18.10101 20.65524 64.11858 100 a
Is it what you want :
> library(partitions)
> 10*restrictedparts(10,8)
[1,] 100 90 80 70 60 50 80 70 60 50 60 50 40 40 70 60 50 40 50 40 30 40 30 60 50 40 40 30 30 20 50 40 30 30 20 40 30 20 30 20
[2,] 0 10 20 30 40 50 10 20 30 40 20 30 40 30 10 20 30 40 20 30 30 20 30 10 20 30 20 30 20 20 10 20 30 20 20 10 20 20 10 20
[3,] 0 0 0 0 0 0 10 10 10 10 20 20 20 30 10 10 10 10 20 20 30 20 20 10 10 10 20 20 20 20 10 10 10 20 20 10 10 20 10 10
[4,] 0 0 0 0 0 0 0 0 0 0 0 0 0 0 10 10 10 10 10 10 10 20 20 10 10 10 10 10 20 20 10 10 10 10 20 10 10 10 10 10
[5,] 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 10 10 10 10 10 10 20 10 10 10 10 10 10 10 10 10 10
[6,] 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 10 10 10 10 10 10 10 10 10 10
[7,] 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 10 10 10 10 10
[8,] 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 10 10