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?
You can use the greedy algorithm to enumerate all elements of the cartesian product 0:2 x 0:3 x 0:5. This algorithm is performed by my function
greedy_backward
below. I am not an expert in Javascript and maybe this function could be improved.It enumerates the elements of the Cartesian product in the anti-lexicographic order (you will see the full enumeration in the
doSomething
example):This is a generalization of the binary representation (the case when
sizes=[2,2,2,...]
).Example:
If needed, the reverse operation is simple:
Example :
Set up an array of counters with the same length as the limit array. Use a single loop, and increment the last item in each iteration. When it reaches it's limit you restart it and increment the next item.