I’m trying to figure out a solution of stacking or “packing” a series of rectangles and squares into blocks of 3x1 or 6x2 so that there isn’t a block with a protruding element and an uneven end. The width of the blocks can be a maximum of 3, before it has to break on another line. Image link below.

I have tried using 3 systems of measurements, Width + Height, Space (Num of single blocks an element occupies) + Width, Space + Height.

There are 5 possible elements that the grid can use. Image link below.

Using the S + H paradigm they are:

Name | Space x Height Large - 4 x 2 Fullwidth - 3 x 1 Horizontal - 2 x 1 Vertical - 2 x 2 Item(Single) - 1 x 1

So far the logic has taken me to the situation that a block will always be either 3x1 or 6x2 . If the spaces taken exceed 3, it means the block must be at least 2 blocks tall, e.g if there is 2 elements with a total of 4 spaces the remaining elements must occupy only 2 spaces.

I've excluded the possibility of 9x3 for simplicity.

Horizontal + Item Horizontal = 2 x 1

2 spaces 1 Tall.

Doesn’t fill out a row so we need another element.

Item = 1 x 1

2 + 1 = 3 Spaces

1 = 1 = 1 Tall

Horizontal + Item = 3x1.

Item + Item + Item 1x1 = 1 Space 1 Tall

1x1 + 1x1 = 2 Spaces 1 Tall

1x1 + 1x1 + 1x1 = 3 Spaces 1 Tall

Item + Item + Item = 3x1.

Horizontal + Horizontal + Vertical 2x1 = 2 Space 1 Tall

2x1 + 2x1 = 4 Space 1 Tall

Spaces are > 3, therefore the block must be 6x2 in the end. There are 4 spaces which means there must be elements added so they occupy 2 more spaces and be 2 tall.

2x1 + 2x1 + 2x2 = 6 Spaces 2 Tall

I’m not sure if I’m close to a solution or way off.

The actual order of which elements are put in first doesn’t matter as I’m using an external library to place them in coherent blocks which handles that logic.

E.g Horizontal + Horizontal + Vertical == Horizontal + Vertical + Horizontal .

The logic will be written in PHP if that helps.

Image link here