Find an optimal n square size (same for each) to f

2019-05-11 17:40发布

Input

Rectangle area width and height, so we could calculate rectangle aspect/proportions.

N is the number of squares that we want to resize using the same size for each.

Output

Find the optimal squares size that would fit most part of our container. For example

containerWidth = 200;
containerHeight = 100;
n = 8;

In this case squaresSize should be 50 to fit most of rectangle area.

What i tried

I already tried to calculate container math area and then divide it to the number of squares to get each square area by taking a square root. But this is the ideal square size, so it douesn't respect each square place relative to container rectangle.

Real purpouse

I trying to make scallable user interface, that would draw as much square objects in rectangle container as it is possible.

2条回答
可以哭但决不认输i
2楼-- · 2019-05-11 18:10

You have to solve inequality (find max value of a)

(Width div a) * (Height div a) >= n

where div is integer division with truncation (8 div 3 = 2)

Result depends monotonically on n, so get first approximation as

a = Sqrt(W*H/n)

and find exact value with linear or binary search

查看更多
Animai°情兽
3楼-- · 2019-05-11 18:11

Let S be the size of each square (width and height). Then you want to solve the optimization problem

  maximize S
subject to floor(Width / S) * floor(Height / S) >= n
           S >= 0

The feasible region is a range [0, S*], where S* is the optimal solution.

We know that S * S * n <= Width * Height for all feasible S; that is, S <= sqrt(Width * Height / n).

So you can simply binary search the range [0, sqrt(Width * Height / n)] for the largest value of S for which floor(Width / S) * floor(Height / S) >= n.

Once you have the optimal S*, you will place your squares into the container in a grid with floor(Width / S*) columns and floor(Height / S*) rows.

查看更多
登录 后发表回答