I made a stackblitz for understand my problem:
https://stackblitz.com/edit/angular-aqmahw?file=src/app/tiles-example.css
I have tiles which can have 4 differents width (25%, 50%, 75%, 100%).
The tiles can only go on 2 lines, so if i have only tiles of 25% width i can have 8 of them.
I’m trying to find an algorithm to find the empty spaces in these 2 lines and what size are these empty spaces.
Because if I add a tile, I want it to be added in these empty spaces only if it has space and I don’t want to add it to the end of the list.
Can someone help me with this algorithm ?
2
Answers
You would be better off to achieve this using
grid
as you can control 2d space instead offlex
1d spaceI rebuilt your example here
https://stackblitz.com/edit/angular-teylho?file=src/app/tiles-example.ts
Ok, here’s what I came up with: https://stackblitz.com/edit/angular-n6dqoj?file=src%2Fapp%2Ftiles-example.ts
Beside your initial
tiles
object, I introduced variables that keep the data you might want changed (or set dynamically at any point):maximumSizePerRow
) that you allow,maximumNumberOfRows
) you want,rowPrefix
) for displaying/logging purpose,along with two arrays of objects that keep the information about rows’ content and are used to handle adding new tiles:
rowsData
that keeps info about the row (name, empty spaces left and names of the tiles that are set into this row),tilesUsed
that keeps only the tiles that are going to be displayed – depending on the number of rows you want to display i.e. tiles that don’t fall into the last allowed row won’t be in this object. This object is then used in template instead of your originaltiles
object.The algorithm is very simple in this case: after initial structure of the
rowsData
is set, the code iterates over the rows objects in that array, and inside each iteration iterates again over the tiles fromtiles
object: if certain criteria is met – it puts the given tile into the row. The criteria is that row size is not full, it has enough space for that particular tile, and the tile is not already used in another row.So in the view you’ll only see the tiles that are used in the allowed number of rows, and the final console log is just a decoration, but shows which data to use to get empty spaces left per row.