Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variable amount of nested for loops

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?

like image 527
pimvdb Avatar asked Jan 13 '11 18:01

pimvdb


People also ask

How many nested loops are possible?

A loop can be nested inside of another loop. C++ allows at least 256 levels of nesting.

How many times nested loops run?

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)…..

How do you calculate nested loops?

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)

How many nested loops are possible in C?

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.


1 Answers

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); 
like image 149
Sean Avatar answered Oct 12 '22 12:10

Sean