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.
You have to solve inequality (find max value of a)
where div is integer division with truncation (8 div 3 = 2)
Result depends monotonically on n, so get first approximation as
and find exact value with linear or binary search
Let
S
be the size of each square (width and height). Then you want to solve the optimization problemThe feasible region is a range
[0, S*]
, whereS*
is the optimal solution.We know that
S * S * n <= Width * Height
for all feasibleS
; that is,S <= sqrt(Width * Height / n)
.So you can simply binary search the range
[0, sqrt(Width * Height / n)]
for the largest value ofS
for whichfloor(Width / S) * floor(Height / S) >= n
.Once you have the optimal
S*
, you will place your squares into the container in a grid withfloor(Width / S*)
columns andfloor(Height / S*)
rows.