0

I have a dynamically created array of Box objects where the user inputs an amount of boxes then enters their dimensions

Each Box object has multiple variables, but I'm interested in finding the box with the highest totalArea variable as i'm trying to figure out which size fills up a space the most efficiently

I can do this very simply with:

int amount = 0, boxNum;

for (int i=0; i<boxes.length;i++)
    if (boxes[i].totalArea > amount){
        amount = boxes[i].totalArea;
        boxNum = i+1;
    }

but I feel as if i'm doing more work than necessary by declaring three variables. I'm wondering if there is a more efficient way to achieve this. My first thought was using an enhanced for loop, but that's a no go, as finding the current index of the iteration isn't a viable route. Now it's probably not a big deal, but for the sake of optimization and learning, is there a better, faster way to do this?

edit: This example is not a duplicate of this question as Collections.max() is used for collections like arrayLists, not generic arrays

  • 4
    Better and faster are not synonymous. You can make the code a little cleaner, perhaps, but not significantly faster. At least not in a single-threaded environment. – shmosel Jul 25 '18 at 04:28
  • Why would a box even have a `totalArea` field? Does it not have dimensions? – shmosel Jul 25 '18 at 04:29
  • If you need to find the maximum area and the index at which it occurs, you do need to have two variables. – Thiyagu Jul 25 '18 at 04:37
  • You do not strictly need the `amount` variable, however, leaving it out would make the program slightly more complicated and slower. – Henry Jul 25 '18 at 04:49
  • @shmosel the program calculates the most efficient size box to fill a larger space. `totalArea` is the area of the box * how many boxes fit in the space. This allows me to find the best fit, plus the percentage of space that is unused – LosOnTheGo Jul 25 '18 at 21:45

0 Answers0