Friday, 13 September 2013

More Efficient Solution - Three Nested FOR Loops (Java)

More Efficient Solution - Three Nested FOR Loops (Java)

I was wondering if there is a more efficient solution to this problem
(some of the variable names have been changed):
for (Object obj: o){
//set the display part to obj
//get all of the items from the obj and place it in an array
for (int i = 0; i < array.size; i++){
if (array[i] instanceof Line){
for (int j = i + 1; j < array.size; j++){
if (array[j] instanceof Line){
//DO SOMETHING
}
}
}
}
}
So this is pseudo code more or less but basically what it is doing is:
Taking in a list of objects (outer for loop)
Getting all of the 'items' from that list with a seperate method and
placing it into an array that will be used in the next two for loops.
Then the second for loops begins going through the items in the array one
by one. If it finds one with the type "Line" then the third for loop
executes.
Finally, the third for loop goes through the same array item by item,
starting at the previous index + 1 (i+1) until it reaches the end of the
array. If it finds and item of type "Line" then it does some calculations
between the two.
Is there a more efficient way of doing this rather than having three
nested for loops? The code works fine and executes fine with a small input
(small object list) but I am worried than if (and when) the input list
gets to be larger this code will take a very long time to execute. Any
input is appreciated, thanks!

No comments:

Post a Comment