I need to speed up this built in loops how can I do please ?
for(M_P in 0:9)
{
for(M_D in 0:(9-M_P))
{
for(M_A in 0:(9-M_P-M_D))
{
for(M_CC in 0:(9-M_P-M_D-M_A))
{
for(M_CD in (9-M_P-M_D-M_A-M_CC))
{
for(G_D in 0:9)
{
for(G_A in 0:(9-G_D))
{
for(G_CC in 0:(9-G_D-G_A))
{
for(G_CD in (9-G_D-G_A-G_CC))
{
for(S_D in 0:9)
{
for(S_A in 0:(9-S_D))
{
for(S_CC in 0:(9-S_D-S_A))
{
for(S_CD in (9-S_D-S_A-S_CC))
{
for(Q_P in 0:3)
{
for(Q_D in 0:(3-Q_P))
{
for(Q_A in 0:(3-Q_P-Q_D))
{
for(Q_CC in 0:(3-Q_P-Q_D-Q_A))
{
for(Q_CD in (3-Q_P-Q_D-Q_A-Q_CC))
{
It's taking forever to compute how can I do please ? I'm only a beginner but I heard that there's maybe something with the apply thing or also with multi cores i have 4cores, i'm using Rstudio please help me. Thank mens !
PS : tell me if you need the rest of code but it's a simple calculation with * and + using all the M_P, M_D etc. If i leave it overnight does it have a chance to end ? I would like to add few loops in that so I would have to do all of this 3 or 10 more times :s
The variables M_xx
, G_xx
, S_xx
and Q_xx
are independent. Also, there is a lot of coincident values generated. I've split these 4 variables in separate loops, then I've generated all combinations considering only unique values. See the code:
M <- NULL
for(M_P in 0:9) for(M_D in 0:(9-M_P)) for(M_A in 0:(9-M_P-M_D)) for(M_CC in 0:(9-M_P-M_D-M_A)) for(M_CD in (9-M_P-M_D-M_A-M_CC))
{
M[length(M)+1] <- 1.1*M_P+2.1*M_D+3.1*M_A+4.1*M_CC+4*M_CD
}
G <- NULL
for(G_D in 0:9) for(G_A in 0:(9-G_D)) for(G_CC in 0:(9-G_D-G_A)) for(G_CD in (9-G_D-G_A-G_CC))
{
G[length(G)+1] <- 2*G_D+5*G_A+1.5*G_CC+3*G_CD
}
S <- NULL
for(S_D in 0:9) for(S_A in 0:(9-S_D)) for(S_CC in 0:(9-S_D-S_A)) for(S_CD in (9-S_D-S_A-S_CC))
{
S[length(S)+1] <- 5*S_D+4*S_A+3*S_CC+6*S_CD
}
Q <- NULL
for(Q_P in 0:3) for(Q_D in 0:(3-Q_P)) for(Q_A in 0:(3-Q_P-Q_D)) for(Q_CC in 0:(3-Q_P-Q_D-Q_A)) for(Q_CD in (3-Q_P-Q_D-Q_A-Q_CC))
{
Q[length(Q)+1] <- 2*Q_P+3*Q_D+2.2*Q_A+3*Q_CC+4*Q_CD
}
max(apply(expand.grid(unique(M), unique(G), unique(S), unique(Q)), 1, sum))