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.
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?
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))
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With