This isn’t a complicated problem, but I can’t for whatever reason think of a simple way to do this with the modulus operator. Basically I have a collection of N items and I want to display them in a grid.
I can display a maximum of 3 entries across and infinite vertically; they are not fixed width…So If I have 2 items they get displayed like that [1][2]. If I have 4 items they get displayed stacked like this:
[1][2]
[3][4]
If I have 5 items it should look like this:
[ 1 ][ 2]
[3][4][5]
Seven items is slightly more complicated:
[ 1 ][ 2]
[ 3 ][ 4]
[5][6][7]
This is one of those things where if I slept on it, it would be brain dead obvious in the morning, but all I can think about doing involves complicated loops and state variables. There has to be an easier way.
I’m doing this in C# but I doubt the language matters.
By maximizing the number of rows that have three items, you can minimize the total number of rows. Thus six items would be grouped as two rows of 3 rather than three rows of 2:
and ten items would be grouped as two rows of 2 and two rows of 3 rather than five rows of 2:
If you want rows with two items first, then you keep peeling off two items until the remaining items are divisible by 3. As you go through the loop, you need to keep track of the number of remaining items using an index or whatnot.
In your loop to populate each row, you can check these conditions:
If we walk through the example of 10 items, the process would go as follows:
To go to your example of 7 items:
And here’s the result for 4 items:
I think that’ll work. At least, at 12:30 a.m. it seems like it should work.