How to achieve N different number of loops in C#?

Hi guys,
I failed to sort out the problem below.How can I accomplish “N different number of loops”?


I’m not sure what you are trying to do but couldn’t the constants be a list of integers?

for(int i=0; i<constants.Count; i++)
    for(int j=0; j<constants[i]; j++)
       //do stuff

Hi Michael,
Thank you for your suggestion.The constants surely can be a list of integers.
But I want “i_a/i_b/i_c/i_d…i_n” to appear at the same time.
“do something” (e.g.):

Hi @niyuxiangken
What you want to achieve is not possible, unless the developers that code the C#language add that feature. In addition, it will also not make sense at all since a nested forloop with N depth will be computationally super inefficient. In BigO notation it will be O(N^N). Something of this magnitude people in computer science will try to avoid at all costs because for large inputs of N such an algorithm will take ages to run. I guess this is also the reason why C# or any other programming language in my knowledge, has not implemented the feature your are thinking of.

1 Like

Adding on to what @rawitscher-torres said, I think your end goal is not impossible, but we don’t know what it is :smiley: . If you actually tell us what your overall goal is to achieve I am sure we can point you in the correct way to achieve it with proper scripting protocols.

Hi Michael,
What I want is below.Exactly,the problem is similar to “Integer Linear Programming”.But I do not need the integer solution of the “Max or Min”,but all the integer combinations that satisfy the inequalities.

Here you solved it, but in the classical brute force search, I wonder if this can be done with other known algorithms… maybe with Binary Search?

not sure. Interesting indeed.

As others have said this is dangerous territory from a performance standpoint — you will wind up with A * B * C * D… * N loops which becomes a very large number very fast. But it is possible to calculate the cartesian product of all these lists and then loop over the results to do your processing. Here are a few examples:

I know enumerating the range of variables is surely not a good way.Thanks for your suggestion.I will do it further.

Hi Andrew,
Thanks for your proposal.I will seriously study this issue.