2013-10-22 81 views
-2

編碼C#時遇到了此問題,但我認爲答案適用於任何編程語言。許多嵌套for循環

我需要多個嵌套循環(比方說9,但可以是100)。我的代碼應該執行這樣的:

for (a1=0;a1<N;a1++) 
for (a2=0;a2<N;a2++) 
... 
for (a9=0;a9<N;a9++) 
    //do something 

我覺得這個代碼可以通過使用可變M=9和int數組短a[]而不是A1,A2,A3,...

你能提供任何提示?

編輯: 我知道我不需要使用嵌套循環來做到這一點。我只是問我是否可以使用變量M=9 int數組a[]以及更少的代碼。

如果你真的需要看到的東西複雜化,我寫了下面的代碼:S4,S5,S10 ...:

 string[] s1 = new string[3]{ "apples", "oranges","bananas" }; 
     string[] s2 = new string[5] { "are", "are not", "should be", "must be","seem to be" }; 
     string[] s3 = new string[3] { "big", "small", "tasty" }; 

     int[] a=new int[10]; 
     int[] step = new int[10]; 
     step[1] = 1; step[2] = 1; step[3] = 2; 
     for (a[1] = 0; a[1] < s1.Length; a[1]+=step[1]) 
      for (a[2] = 0; a[2] < s2.Length; a[2]+=step[2]) 
       for (a[3] = 0; a[3] < s3.Length; a[3]+=step[3]) 
        Console.WriteLine(s1[a[1]] + " " + s2[a[2]] + " " + s3[a[3]]); 

與多個陣列想像這一點。 (這可能是陣列s[]的陣列,或者二維陣列s[,]

+4

你需要'100'來循環。你確定?這聽起來像是對我來說X,Y問題的一個地獄。解釋你想要做什麼。 – christopher

+4

聽起來像遞歸問題,但你必須對你的問題更具體。你給我們你的解決方案,但不是你的問題。我們可能完全有不同的解決方案。 –

+0

你需要做9次或者需要9次循環嗎? – DGibbs

回答

5

limits數組定義了每個組件的上限(-1,相當於< N中的for循環)。組件數組保存每個組件的值。

int[] limits = { 9, 20, 15, 30, 8, 40, 10 }; 
int[] components = new int[limits.Length]; 

bool done = false; 
while (!done) 
{ 
    //do work here using the components 
    int M = components[0]; 
    int N = components[1]; 
    int O = components[2]; 
    int P = components[3]; 
    //etc 
    //first iteration M=0,N=0,O=0, etc 

    //this part does the incrementing for the next iteration 
    for (int j = 0; j < limits.Length; j++) 
    { 
     components[j]++; 
     if (components[j] < limits[j]) 
      break; 
     components[j] = 0; 
     if (j == limits.Length - 1) 
      done = true; 
    } 
} 
+0

謝謝!這就是我一直在尋找的東西。經常使用嗎?我的意思是,在某些教程或示例中可以找到它,或者現在只編寫它? –

+0

我現在編碼,但從記憶中我不得不在過去一次這樣做。從人們對這個問題的反應可以看出,這很不尋常...... –

0

您的代碼

for (a1=0;a1<N;a1++) 
for (a2=0;a2<N;a2++) 
... 
for (a9=0;a9<N;a9++) 

可以用這個來代替:

int M = 9; 
    int N = 20; 
    int index = 0; 


    for (int x = 0; x < M; x++) 
    { 
     for (int y = 0; y < N; y++) 
     { 
      // do something 
      // perhaps a[index++] = some value; 
     } 
    } 

有更好的解決方案的問題,但我認爲這是你所要求的。

+0

好。現在想象M = 9,N = 20,O = 15,P = 20,Q = 30,所有這些嵌套。 –

+0

這不是你的原始問題。爲什麼不簡單地將M,N,O等等總結爲一個變量? – user1567896

+0

是的,這是我的原始問題。有9個嵌套循環,而不是2.然而,如果你現在真的明白我想要什麼,你能提供一個解決方案嗎? (每個變量都代表「做某事」的不同部分,我不只需要做相同的事情9 * 20 * 15 * 20 * 30次 –