Organizing objects in a near-square pattern

185 Views Asked by At

I don't have any fixed constraints but just a general idea. This probably a well known problem too - yet I can't seem to find any literature on it.

Given n identical 2D objects, what is an algorithm to arrange them on the plane such that they form a near square ? Leaving a hole at the end (e.g. in the case of prime numbers, but not only) is acceptable (hence the word near) but having some objects "sticking out" to the right is not okay - though this is often a variant of another arrangement, simply rotated 90°.

The final shape may actually be a rectangle, let's see how much the dimensions can differ and if we need to put a constraint on that.

e.g. for n = 4 :

1 2
3 4

n = 6

1 2 3
4 5 6

or

1 2
3 4
5 6

n = 8 perfect 3x3 square with one hole

1 2 3
4 5 6
7 8

n = 10

1  2  3

4  5  6

7  8  9

10

or

1  2  3  4

5  6  7  8

9  10

but not

1  2  3

4  5  6

7  8  9  10

which is anyway the first arrangement turned 90°.

... and so on.

1

There are 1 best solutions below

0
On BEST ANSWER

Find out which two consecutive squares $n$ lies between, i.e. $m^2\le n < (m+1)^2$. You can find $m$ by calculating $m=\lfloor \sqrt{n} \rfloor$.

Then calculate the surplus $k=m^2-n$. Obviously we have $0\le k<2m+1$ because $(m+1)^2-m^2=2m+1$.

If $0\le k<m$, you can form an $m\times m$ square with an extra row of $k$ units underneath.

If $m \le k<2m+1$ then first add a column to the right of the square to form an $m\times (m+1)$ rectangle, and then add the remaining $k-m$ as a partial row underneath. This is then an $(m+1)\times (m+1)$ square with part of the last row missing.