-2

我需要加速这个内置循环我该怎么做?

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))
                              {

它需要永远计算我该怎么做?我只是一个初学者,但我听说应用程序或多核可能有问题,我有 4 核,我正在使用 Rstudio,请帮助我。感谢男士!

PS:告诉我您是否需要其余代码,但这是使用所有 M_P、M_D 等使用 * 和 + 进行的简单计算。如果我将其放置一夜,它是否有机会结束?我想在其中添加几个循环,所以我必须再做 3 到 10 次:s

4

1 回答 1

0

变量M_xxG_xx和是独立的S_xxQ_xx此外,还会生成许多重合值。我已将这 4 个变量拆分为单独的循环,然后生成所有组合,仅考虑唯一值。见代码:

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))
于 2013-06-04T14:03:15.843 回答