Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find an optimal n square size (same for each) to fit most part of rectangle container

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.

like image 298
user3388811 Avatar asked Oct 15 '25 04:10

user3388811


2 Answers

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

like image 95
MBo Avatar answered Oct 18 '25 03:10

MBo


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.

like image 32
Timothy Shields Avatar answered Oct 18 '25 03:10

Timothy Shields