3

I'm looking for a simple algorithm that, given a rectangle with width w and height h, splits the rectangle into n more or less equal sized and shape rectangles and calculates the center of these rectangles.

EDIT: Forgot to mention that the shapes should be as similar as possible to a square.

Any hints how to start?

3
  • 2
    @mark's answer meets your requirements, but I'm wondering if you have more constraints on "shape"? Commented Feb 6, 2011 at 14:09
  • @payne: yes Mark's answer meets the stated requirements but I forgot to remark that the new shapes should be as similar to a square as possible. Commented Feb 6, 2011 at 14:12
  • I suspected as much, thank you for the clarification. :-) Commented Feb 6, 2011 at 14:16

1 Answer 1

8

A simple algorithm is to split vertically into n equal sized strips of height h and width w/n.

If you assume that the initial rectangle has corners (0,0) and (w,h) then using this algorithm the ith rectangle would have center (w / n * (i + ½), h/2), for 0 <= i < n.


Update: try finding all the factorizations of the number n into factor pairs (i, j) such that i * j = n, and find the factor pair such that the ratio of the factors is closest to the ratio of the sides of the rectangle. Then use the two factors to create a regular grid of smaller rectangles.

For example when n is 10, you can choose between (1, 10), (2, 5), (5, 2) and (10, 1). Here is an example grid using the factors (5, 2):

------------------------------------
|      |      |      |      |      |
|      |      |      |      |      |
------------------------------------
|      |      |      |      |      |
|      |      |      |      |      |
------------------------------------

If your initial rectangle has width 60 and height 20 then using the factor pair (5, 2) will give ten rectangles of size (60/5, 20/2) = (12, 10) which is close to square.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks. This is the correct answer, but I forgot to mention another requirement. Sorry.
Thanks a lot for the update. I understand this factor pairs. Do you have a good recommendation how to choose a factor pair? Maybe the factor pair with the smallest distance between i and j?
And another question. Do you have any idea how to handle odd n? For example n = 11, width = 400 height = 400. Then Your algorithm calculates 11 squares in a row. But better would be for example 2 X 5 and one square int the 3. row.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.