We have a list of "stories", each is an html block and its size is either 1x1, 2x1, 2x2 or 4x2. We need to fit them in a grid that is 8x3. We need to respect the order of the list as long as they can fit the grid, otherwise stories are skipped.
Our algorithm creates an array of arrays that represents each cell in the grid. Initially all cells as set to false to represent that they are empty.
We create an array of boxes, to represent our list of stores. Each box has a width and height, which can be one of the four sizes: 1x1, 2x1, 2x2 or 4x2
We use a pointer element that has the grid coordinates of the next open space.
The algorithm sweeps the boxes list. On each item it checks if the box fits in the grid at all from the current pointer position. If it does fit, then it checks that all the cells needed by the box are still empty. If yes, then the box is placed, the grid array is updated, and the pointer is moved to the next open spot.
When we are unable to place a box we jump ahead it in the list until we find a box that we can place in the space. Once we are able to place a box, we return to the first box that was not place and try with it again.
Placing on the grid is done by setting the CSS left/top and width/height properties.
This algorithm accounts for edge situations like running out of boxes before filling the grid, and unable to place any boxes while still having space (but all available boxes are larger)