Edit: I'm sorry, but I forgot to mention that I'll need the values of the counter variables. So making one loop isn't a solution I'm afraid.
I'm not sure if this is possible at all, but I would like to do the following. To a function, an array of numbers is passed. Each number is the upper limit of a for loop, for example, if the array is [2, 3, 5]
, the following code should be executed:
for(var a = 0; a < 2; a++) { for(var b = 0; b < 3; b++) { for(var c = 0; c < 5; c++) { doSomething([a, b, c]); } } }
So the amount of nested for loops is equal to the length of the array. Would there be any way to make this work? I was thinking of creating a piece of code which adds each for loop to a string, and then evaluates it through eval
. I've read however that eval
should not be one's first choice as it can have dangerous results too.
What technique might be appropriate here?
A loop can be nested inside of another loop. C++ allows at least 256 levels of nesting.
Two nested loops: O(n²) In the above nested loop example, outer loop is running n times and for every iteration of the outer loop, inner loop is running (n - i) times. So total number of nested loop iteration = (n - 1) + (n - 2) + (n - 3)…..
To count statements in nested loops, one just separates the counts for the iterations of the outer loop, then adds them: count (nested loop) = count (1st iteration of the outer loop) + count (2nd iteration of the outer loop) + … + count (last iteration of the outer loop)
Strictly, the C standard does not limit the number of loops; it places a lower bound on the number of nested loops that must be supported. Anything with 6200 nested loops is mind-boggling.
Recursion can solve this problem neatly:
function callManyTimes(maxIndices, func) { doCallManyTimes(maxIndices, func, [], 0); } function doCallManyTimes(maxIndices, func, args, index) { if (maxIndices.length == 0) { func(args); } else { var rest = maxIndices.slice(1); for (args[index] = 0; args[index] < maxIndices[0]; ++args[index]) { doCallManyTimes(rest, func, args, index + 1); } } }
Call it like this:
callManyTimes([2,3,5], doSomething);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With