Last active
August 25, 2016 18:40
-
-
Save Coding-Enthusiast/766ac595cc3a809e527b49caaa818210 to your computer and use it in GitHub Desktop.
Nested loop with variable number of loops and variable lengths
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//we have a List<int> SuperList that is generated seperately and | |
// contains the number of loops and their lengths e.g. {3, 5, 2} | |
//and our loop should be like this: | |
//for (int i = 0; i < 3; i++) | |
// for (int j = 0; j < 5; j++) | |
// for (int k = 0; k < 2; k++) | |
// //use i, j, k in a function | |
List<int> SuperList = new List<int>(); | |
int max = 1; | |
private void LoopFunc() | |
{ | |
foreach (var item in SuperList) | |
{ | |
max *= item;//max is the maximum number of all the loops (each time a set of i,j,k,... is created) | |
} | |
//this is the list of indexes possible for each loop | |
List<int[]> finalList = new List<int[]>(); | |
//these are the first indexes which will be created after the "first" loop (all zero) | |
int[] firstIndex = new int[SuperList.Count]; | |
for (int i = 0; i < SuperList.Count; i++) | |
{ | |
firstIndex[i] = 0; | |
} | |
finalList.Add(firstIndex); | |
//now the loop | |
for (int i = 1; i < max; i++) | |
{ | |
finalList.Add(TheLoop(finalList[i - 1])); | |
} | |
//now do some stuff to finalList items | |
} | |
private int[] TheLoop(int[] myList) | |
{ | |
//this is done because because array is passed by reference | |
//and i could not come up with a better solution! | |
int[] tempList = new int[myList.Length]; | |
for (int i = 0; i < myList.Length; i++) | |
{ | |
tempList[i] = myList[i]; | |
} | |
//now generate the loop (indexes) | |
int lastIndex = tempList.Length - 1; | |
tempList[lastIndex]++; | |
for (int i = lastIndex; i >= 0; i--) | |
{ | |
if (tempList[i] < SuperList[i]) | |
{ | |
break; | |
} | |
else | |
{ | |
tempList[i] = 0; | |
tempList[i - 1]++; | |
} | |
} | |
return tempList; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment