Is there a way to use a loop to create more nested loops? E.g. Doing this
for (int i = 0; i < iterations; i++)
{
//Do stuff
for (int ii = 0; ii < iterations; ii++)
{
// Do stuff
for (int iii = 0; iii < iterations; iii++)
{
//Do Stuff
}
}
}
but allowing the user to change how many nested loops you want during run-time.
This allows me to know the depth I am on, while also resetting the "i" counter back to 0, allowing me to do the exact same thing over again, but with a different depth value.
2 Answers 2
There is a way! You can solve such problems with recursion (https://en.wikipedia.org/wiki/Recursion_%28computer_science%29).
In your case it would look something like this (pseudocode):
function doStuff(int depth) {
if(depth > USER_DEFINED_DEPTH)
return;
//Do stuff
doStuff(depth + 1);
}
doStuff(0);
-
Another (uglier) way is to use self modifying code. A simple example could be written with shell scripts. Script A would write Script B, then execute Script B. (Not a recommended practice - debugging could be a nightmare).Dan Pichelman– Dan Pichelman2015年06月29日 01:21:26 +00:00Commented Jun 29, 2015 at 1:21
-
Suggesting JS recursion in a C# question might not be the best idea, since you risk blowing the stack.Magus– Magus2015年06月29日 15:06:41 +00:00Commented Jun 29, 2015 at 15:06
You've gotten some good answers here and on SO to your questions, but you're missing a non-recursive solution. Here's how I went about trying to solve the problem (Note that it is currently slightly broken!):
private static IEnumerable<string> GetPaths(int maxDepth, int iterations, string root)
{
var depths = Enumerable.Range(0, maxDepth);
var widths = Enumerable.Range(0, iterations);
var thing = depths.Select(x => Path.Combine(
depths
.Reverse()
.Skip(x + 1)
.Select(y => y.ToString())
.Reverse()
.ToArray()));
return thing.SelectMany(x => widths.Select(y => Path.Combine(root, x, y.ToString())));
}
What this essentially does is create all the sets of combinations by joining collections, and then combines them into paths. The result is that every depth is covered, without any chance of blowing the stack. There is a bug currently: the variable thing
(which should be renamed, should you take this route) contains (with an input of 10, 10, "temp"
the paths:
01円2円3円4円5円6円7円8円
01円2円3円4円5円6円7円
01円2円3円4円5円6円
01円2円3円4円5円
01円2円3円4円
01円2円3円
01円2円
01円
0
string.Empty
I'll leave it to you to figure out how to fix it, but it's very simple.
-
Note that if you don't want iterations to be passed in separately, you can probably get this down to just two arguments, and use
maxDepths
for widths as well, or even just have the singledepths
collection and use that in the finalSelectMany
.Magus– Magus2015年06月30日 17:19:49 +00:00Commented Jun 30, 2015 at 17:19
iterations
and an argument. We'd need to see what stuff you need to do to be able to give a really good answer.