Search code examples
javascriptcssalgorithmgeometrypacking

Splitting square div in to n smaller divs algorithm


I have a square container div with width & height set to 200px. I will receive a number (e.g. 3, 10, 20, 30) and need to create that number of rectangular or square divs within the container div to fill up the space.

Question:

How can I find the width & height of these inner divs, assuming there is no extra space (margins and padding) in between? Ideally, they should be as close to squares as possible.

Example:

if the number is 100, the inner width and height would be 20px, fairly straightforward. If the number is 3, the inner width could be 33% and the height could be 100%, or vice versa.


Solution

  • I think the idea would be to find the pair of divisors (complementary divisors) that is as close as possible to each other. In other words this would be the pair of divisors having the minimal sum.

    For 3 this would be 1 and 3.

    20 can be obtained by multiplication of the pairs 1×20, 2×10, 4×5 (and symetries). The pair wit the closest divisors (or sum of divisors) is 4x5.

    For 30 (1x30, 2x15, 3x10 and 5×6) you will get 5x6.

    Once you have the pair of divisors you know how to stack the boxes and can calcolate the width and height of each box.

    For 30 for example you will want to have 5 rows and 6 columns of boxes (or the other way around). So you divide 200 by 5 and get the height of a box and 200 by 6 gives you the witdh.

    You might have to round to pixels in the end.