Basically what I am trying to do is a N nested for loops, where N is an input variable. How to write a single piece of codes to take care of different N?
Thanks!
8 10322 Meetee 931
Recognized Expert Moderator Contributor
Basically what I am trying to do is a N nested for loops, where N is an input variable. How to write a single piece of codes to take care of different N?
Thanks!
I am not clear with your explanation. You want to make N for loops!!!??? You mean to say you want to run N nested loops?? Kindly elaborate.
Regards
I am not clear with your explanation. You want to make N for loops!!!??? You mean to say you want to run N nested loops?? Kindly elaborate.
Regards
For example, if N = 2, we want a two layer nested loop.
for (int i = 0; i < 10; i++)
for (int j = 0; j < 20; j++)
{
......
}
if N=3, we want a three layer nested loop
for (int i = 0; i < 10; i++)
for (int j = 0; j < 20; j++)
for (int k=0; k< 30; k++)
{
......
}
So on and so forth. Since N can take any value between 1 and 10, I have to write 10 different nested loops, each for a value of N. It is no good. It would be great if there is a way to use one single piece of codes to do all the business.
Thanks.
Banfa 9,065
Recognized Expert Moderator Expert
I would say you have 2 options
1. Use a recursive function, that is a function taht calls itself to set up the right number of for loops
2. Use a single for loop, calculate the total number of iterations that your 'nested' loops would give and loop for that many iterations and calculate the values of i' j' k ... on each iteration of the loop.
JosAH 11,448
Recognized Expert MVP
2. Use a single for loop, calculate the total number of iterations that your 'nested' loops would give and loop for that many iterations and calculate the values of i' j' k ... on each iteration of the loop.
That could cause integer overflows earlier than you'd expected them. There's
a third way: use three int arrays:
1) lo: containing the low values of the n loops
2) hi: containing the hi values of the n loops
3) val: initially equal to array lo.
The following little function produces the next values in array val: if the last values
have been reached already the method returns NULL -
int[] loopn(int[] lo, int[] hi, int[] val, int n) {
-
int i;
-
for (i= n; i-- > 0; )
-
if (++val[i] >= hi[i])
-
val[i]= lo[i];
-
else
-
return val;
-
return NULL;
-
}
kind regards,
Jos
Thanks for your helps.
For the third method, I do not think it goes through all the combination of the values of i,j,k....
Am I right?
I came across this earlier today and thought I might share the solution that I eventually came up with. (I realise that this question is 6 years old, but I'm thinking it might still come in handy for somebody one day!)
I think it should be pretty efficient. Also, it doesn't use any specific c++ stuff - it will work fine on C as well.
We're trying to create N nested "for" loops.
Instead of using -
for(int i = 0; i<max; i++)
-
for (int j = 0; j<max; j++)
-
...
-
I'll be replacing i, j, ... with an array: i[0], i[1], ..., i[n-1].
Here's my solution: -
const int n = /*Insert N here: how many loops do you need?*/;
-
int i[n+1]; // if "n" is not known before hand, then i[n+1] will need to be created dynamically.
-
//Note: there is an extra element at the end of the array, in order to keep track of whether to exit the array.
-
-
for (int a=0; a<n+1; a++) {
-
i[a]=0;
-
}
-
-
int MAX = 79; //That's just an example, if all of the loops are identical: e.g. "for(int i=0; i<79; i++)". If the value of MAX changes for each loop, then make MAX an array instead: (new) int MAX [n]; MAX[0]=10; MAX[1]=20;...;MAX[n-1]=whatever.
-
-
int p = 0; //Used to increment all of the indicies correctly, at the end of each loop.
-
while (i[n]==0) {//Remember, you're only using indicies i[0], ..., i[n-1]. The (n+1)th index, i[n], is just to check whether to the nested loop stuff has finished.
-
//DO STUFF HERE. Pretend you're inside your nested for loops. The more usual i,j,k,... have been replaced here with i[0], i[1], ..., i[n-1].
-
//DO STUFF
-
//DO STUFF
-
-
//Now, after you've done your stuff, we need to incrememnt all of the indicies correctly.
-
i[0]++;
-
// p = 0;//Commented out, because it's replaced by a more efficient alternative below.
-
while(i[p]==MAX) {//(or "MAX[p]" if each "for" loop is different. Note that from an English point of view, this is more like "if(i[p]==MAX". (Initially i[0]) If this is true, then i[p] is reset to 0, and i[p+1] is incremented.
-
i[p]=0;
-
i[++p]++; //increase p by 1, and increase the next (p+1)th index
-
if(i[p]!=MAX) {
-
p=0;//Alternatively, "p=0" can be inserted above (currently commented-out). This one's more efficient though, since it only resets p when it actually needs to be reset!
-
}
-
}
-
}
-
There, that's all. Hopefully the comments make it clear what it's meant to be doing. I think it should be pretty efficient - almost as much as real nested for-loops. Most of the overhead is a one-off at the beginning, so this should be more efficient that using recursive functions etc.
Hope it's useful to somebody one day.
Peace and love.
This solution is WAY too complicated. All that's needed is a function that calls the correct number of loops with the correct number of iterations.
So write a loop function: - void loop(int N)
-
{
-
switch (N)
-
{
-
case 10:
-
loopi(N);
-
break;
-
case 20:
-
loopj(N);
-
break;
-
case 30:
-
loopk(N);
-
break;
-
} /* end of switch */
-
}
-
This function tests the value of N and then calls a secondary function using the value of N.
So all the user needs is to call this function with N: - int main()
-
{
-
int N = 30;
-
loop(N);
-
-
N = 20;
-
loop(N);
-
-
-
N = 10;
-
loop(N);
-
-
}
The secondary functions know about the nested loops and the iterations of the nested loops: - void loopi(int N)
-
{
-
//do loop i and return
-
printf("Loop i %d\n", N);
-
return;
-
}
-
void loopj(int N)
-
{
-
loopi(N - 10);
-
// do loop j
-
printf("Loop j %d\n",N);
-
return;
-
}
-
void loopk(int N)
-
{
-
loopj(N - 10);
-
//do loop k
-
printf("Loop k %d\n", N);
-
return;
-
}
You might run this code to get a feel for how it works.
Banfa 9,065
Recognized Expert Moderator Expert
@weaknessforcats your solution only allows for up to 3 nested loops but the solution calls for up to N nested loops.
@BugMeNot2013 I disagree with weaknessforcats I think your code is not complex enough since it fails to achieve the required solution. Note that in the original question the first loop has an iteration limit of 10, the second 20, the third 30 etc. This behaviour is not demonstrated in your code. Also I think your are wrong at line 19 because the you repeated run the if at 24 and then always (by the logic of the loop) run the assignment at 25. The best you do is replace an assignment with a single if when i[0]<MAX but generally conditionals (if) are less efficient than assignments. I think this is a case of trying to be too clever.
I suspect the solution suggested by JosAH is probably the best although I find the logic of his code snippet strange/wrong.
Sign in to post your reply or Sign up for a free account.
Similar topics |
by: Oleg Leschov |
last post by:
Could there be means of exiting nested loops in python?
something similar to labelled loops in perl..
I consider it irrating to have to make a flag for sole
purpose of checking it after loop if...
|
by: Xah Lee |
last post by:
# -*- coding: utf-8 -*-
# Python
# David Eppstein of the Geometry Junkyard fame gave this elegant
# version for returing all possible pairs from a range of n numbers.
def combo2(n):
return...
|
by: Neptune |
last post by:
Hello.
I am working my way through Zhang's "Teach yourself C in 24 hrs (2e)"
(Sam's series), and for nested loops, he writes (p116) "It's often
necessary to create a loop even when you are...
|
by: Pavan |
last post by:
Hi
i have two nested loops as shown below:
1.
for(i=0;i<=1000;i++)
{
for(i=0;i<=100;i++)
{
.....;
.....;
}
|
by: Roshawn |
last post by:
Hi,
I am experimenting with nested For...Next loops. My code looks like this:
Dim i as Byte
Dim itm as Byte
For i = 0 to 9
For itm = 0 to 9
'code omitted
| |
by: Peter Olcott |
last post by:
http://www.tommti-systems.de/go.html?http://www.tommti-systems.de/main-Dateien/reviews/languages/benchmarks.html
The above link shows that C# is 450% slower on something as simple as a nested
loop....
|
by: tzuriel |
last post by:
Hello all,
I think nested loops will do what I want, but I can't seem to get them
right.
I have two tables, members and casts. I run a query as follows:
$sql_query="SELECT DISTINCT...
|
by: rkc |
last post by:
Hi,
I need to design the following pattern using just the 'for' and the 'if, else' statement. Please provide some help.. thanks in advance:
**********
!*********
!!********
!!!*******...
|
by: toddlahman |
last post by:
I am using two while loops that are nested. The first loop (post name)
returns the full column of results, but the second (post modified)
only returns the first row of the column. Is there another...
|
by: marktang |
last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
|
by: Hystou |
last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
| |
by: Hystou |
last post by:
Overview:
Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
|
by: agi2029 |
last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
|
by: isladogs |
last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM).
In this session, we are pleased to welcome a new...
|
by: conductexam |
last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
|
by: TSSRALBI |
last post by:
Hello
I'm a network technician in training and I need your help.
I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs.
The...
|
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
| |
by: 6302768590 |
last post by:
Hai team
i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated ...
| | |