+ 7

How do I reduce a nested for loop into one loop?

I am required to form pairs of the form (a,b) from the elements present in an array. So I wrote this: // consider array int a[] is defined with distinct elements // N is the number of elements in the array for(i=0;i<N-1;i++) { for(j=i+1;j<N;j++) { // some work with a[i] and a[j] } } } But I really need to reduce this into one loop so that it takes less time to execute. How can I do that? Complete code: https://code.sololearn.com/cv9nq13f9RcK/#cpp

17th Sep 2018, 3:18 AM
Abhishek Tandon
Abhishek Tandon - avatar
3 odpowiedzi
0
You can use i+1 in place of j and then remove the for of j. Not sure if it will take less time to execute though.
18th Sep 2018, 2:22 AM
Alexander Santos
Alexander Santos - avatar
0
What kind of work you will do with a[i] and a[j]?Everything can change depending on that. There is an article to speed up the loops https://www.quora.com/How-can-we-speed-up-the-loop-execution-time-of-nested-loops
18th Sep 2018, 5:07 AM
KarSah
KarSah - avatar
- 3
What kind of work you will do with a[i] and a[j]?Everything can change depending on that. There is an article to speed up the loops https://www.quora.com/How-can-we-speed-up-the-loop-execution-time-of-nested-loops
23rd Sep 2018, 1:29 PM
Rajesh Kumar
Rajesh Kumar - avatar