-5

I have a rectangle, and a list of other rectangles. I want to get the rectangle from the list, that has the best width, height, and aspect ratio according to my rectangle.

Example After I run my code, the best rectangle should be rectangle 3. Note that the rectangle 1 is my rectangle but rotated. enter image description here

What I tried (checking for closest width + height value )

    Rectangle myRectangle = new Rectangle(......)
 Rectangle[] rectangles = new Rectangle[] {
     new Rectangle(.....), new Rectangle(....).......
 };
 int bestRectangle = 0;
 float min = 999999;
 for (int i = 0; i < rectangles.length; i++) {
     float difference = myRectange.width + myRectangle.height - rectangles[i].width - rectangles[i].height;
     if (Math.abs(difference) < min) {
         min = (Math.abs(difference); bestRectangle = i;
         }
     }

The problem with this, is that the best rectangle from my image will be rectangle 1..

Has anyone got a better ideea?

Boldijar Paul
  • 5,405
  • 9
  • 46
  • 94
  • Calculate difference for width and height separately – Alexander Smirnov Jul 14 '14 at 09:48
  • You need to define your algorithm: What is more important: ratio or lengths? You can have the same ratios but vastly different lengths.. – TaW Jul 14 '14 at 09:50
  • @TaW both. I tried with the algorithm of this class https://github.com/libgdx/libgdx/blob/master/gdx/src/com/badlogic/gdx/assets/loaders/resolvers/ResolutionFileResolver.java that should do the same thing, but the first rectangle is also the one choosen. – Boldijar Paul Jul 14 '14 at 09:52
  • float min = float.PositiveInfinity – Dennis_E Jul 14 '14 at 09:53
  • @Dennis_E that won't change a thing.. only if my rectangles are way bigger.. – Boldijar Paul Jul 14 '14 at 09:54
  • That's not good enough to write code. There are many ways to code something, it is up to you to define precisely what you want. If both are important you still have to weigh them! – TaW Jul 14 '14 at 09:55
  • @Paul I know it won't change anything. It is just common practice to initialize a minimum value with infinity (or int.MaxValue in case of ints) My comment wasn't trying to solve anything, just to give a tip. – Dennis_E Jul 14 '14 at 10:00

1 Answers1

1

You are not subtracting the heights and also calculate the absolute differences. Instead of this:

float difference = myRectange.width + myRectangle.height - rectangles[i].width + rectangles[i].height;

use this:

float difference = Math.abs(myRectange.width - rectangles[i].width) + Math.abs(myRectangle.height - rectangles[i].height);

You are not using aspect ratio in your approach though. You should add it also in your condition.

Eypros
  • 5,370
  • 6
  • 42
  • 75
  • Thanks, i wanted to do that, edited my question, i just wrote the algorithm in my mind out there..but there will be the same result.. – Boldijar Paul Jul 14 '14 at 09:56