Reputation: 1
I've recently realized the power of object oriented programming, but don't know how to get around using a nested loops (I've read it is bad programming practice) that takes to much time to execute and is inefficient. I just want to read through objects say Apples, Oranges, and Tomatos. Each object would have a vector of prices for them. My main class would simply loop through all the vector prices and try to find the combinations that are less than say $1,000. This would require three for loops. The real program which I haven't yet wrote would have 10 nested loops.
Upvotes: 0
Views: 53
Reputation: 26946
Not always nested loops are a bad programming practice. As an example consider a game with a board of 10x10 cells. Each cell store an information. If you need to count all the cells having a particular value doing a nested loop can be necessary and it is not a bad practice and it is not inefficient, because you need a way to check all the 100 existing cells (10x10 that can be looped as 10 rows of 10 cells, with a 2 level nested loops).
In your case if you have 3 lists of prices and you would like to find all possible combinations of prices so that you have no more than $1,000 you need to do the nested loops. It is possible to limit the number of checks for example sorting the prices, but the code would be a lot more complicated to be read. And if you don't have to do with special performance issues having a clean code is better than having a more performant code. So don't spend your time trying to have a more performant code before knowing that you need a more performant code. Remember that 80% of execution time is spent in less than 20% of code.
Consider that the 3 nested loops are possible only if you need to find the combinations with 1 apple, 1 orange, and 1 tomato. If you need also other combinations (like 4 apples and 2 oranges and 0 tomatoes) the algorithm will complicate a lot and can not be handled with just 3 nested loops.
Upvotes: 1