Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split a rectangle into equal sized rectangles?

Tags:

c

cgrect

I need to split a rectangle (A CGRect structure which is {{float x,float y},{float w,float h}}) into a number of smaller rectangles/structures, creating some sort of a grid. I'm writing a window layout manager and I want a window preview option.

enter image description here

I saw similar questions but none of the algorithms I saw (the ones involving ceil and floor) worked. I've also tried:

float widthOfNewRect = total.size.width / floor(sqrt(n));
float heightOfNewRect = total.size.height / ceil(sqrt(n));

Can someone provide an example of doing it with my structure in C?

like image 281
Kristina Brooks Avatar asked May 31 '11 15:05

Kristina Brooks


1 Answers

Based on your last comment, I assume that you want to split your rectangle into n subrectangles of equal size, and that they should be aligned in such a manner that the number of rows and number of columns are equal (with the last row possibly not being completely filled). If so, you can use ceil(sqrt(n)) to compute the number of columns (since this is, as you apparently have guessed, the smallest amount of columns you need in order to not have more rows than columns). Then, the number of rows you need in order to accommodate n elements distributed across numColumns columns will be given by ceil(n / (double)numColumns).

As for the code you showed: the reason it doesn't work is (as you probably discovered yourself) that floor(sqrt(n)) * ceil(sqrt(n)) may well be less than n; for instance, this is the case for n = 7. The calculation I propose is a safer way to (indirectly) discover whether the number of rows should be ceil(sqrt(n)) or floor(sqrt(n)).

like image 166
Aasmund Eldhuset Avatar answered Oct 12 '22 23:10

Aasmund Eldhuset