編碼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[,]
你需要'100'來循環。你確定?這聽起來像是對我來說X,Y問題的一個地獄。解釋你想要做什麼。 – christopher
聽起來像遞歸問題,但你必須對你的問題更具體。你給我們你的解決方案,但不是你的問題。我們可能完全有不同的解決方案。 –
你需要做9次或者需要9次循環嗎? – DGibbs