Calculate height for rows of rectangles within a given width

40 Views Asked by At

I have an array of rectangles, all of the same height, but with different widths. Imagine they are on a single line with a uniform gap between them as shown below...

|XXX| |X| |XXXXX| |XXX| |XXXXX| |XXXX| |XX|

Lets say the rectangles are 10units high, so the resulting rectangle for the above array of rectangles would be whatever its width was ( say 400 ) and 10 units high

Imagine however, these recangles must fit within a specified width and are stacked to accomodate this...

example 1

|<---------max width-------->|

|XXXXX| |XXXX| |XX|

|XXX| |X| |XXXXX| |XXX|

so this would be 20 units high ( 2 rows of rectangles )

example 2

|<-----max width---->|

|XXXX| |XX|

|XXX| |XXXXX|

|XXX| |X| |XXXXX|

Gravity isn't in the equation so if the rectangles are top heavy it doesn't make any difference e.g.

|XXXXXXXX|

|XX|

is fine.

I can calculate the height by looping through each rectangle, getting the x position and where necessary ( as its hit the boundary ) stacking onto the next level. Once at the last rectangle I can get the height. However this means for every given max width, I need to recalculate.

Is it possible to put this into a formula, and be able to calculate the resulting height, for any width, without having to iterate through each rectangle?

1

There are 1 best solutions below

3
On

I do not think that you can avoid inspecting the elements at least once.

However if this is a procedure which acts on the same sequence of given rectangles and has to be repeated a lot of times for a limited number of different widths, one might benefit from in advance calculation or using a cache.

And it would be enough to store the result as sequence of the resulting line break positions.