Dividing items into columns
c#
Solution
Assuming that you want to evenly distribute any remainders, this will do the job:
string[] s = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" };
// create the 4 buckets with equal distribution
var buckets = Enumerable.Repeat(s.Length / 4, 4).ToArray();
// distribute any remainders evenly starting from the first bucket
var rem = s.Length % 4;
for (var i = 0; i < rem; i++) buckets[i]++;
var idx = 0;
Console.WriteLine("<ul>");
foreach (var bucket in buckets)
{
Console.WriteLine("\t<li>");
foreach (var _ in Enumerable.Range(1, bucket))
{
Console.WriteLine("\t\t{0}", s[idx++]);
}
Console.WriteLine("\t</li>");
}
Console.WriteLine("</ul>");
For the above code, here is what some edge cases return.
`{}` = 4 empty items in list
`{ "1", "2", "3"}` = 1, 2, 3 in the first three items, fourth item empty
`{ "1", "2", "3", "4", "5"}` = 1, 2 in the first item, 3, 4, 5 in the other items
Problem
I have a dynamic number of items to divide into a maximum of 4 columns, with the proper html format surrounding then, lets say: ``` string[] s = { "1", "2", "3", "4", "5", "6", "7", "8", "9" }; // from 1 to n itens ``` To format into this html: ``` <ul> <li> 1 2 3 </li> <li> 4 5 </li> <li> 6 7 </li> <li> 8 9 </li> </ul> ``` Edit: my website problem: If you have words as itens, putting the itens this way will organize the words into alphabetically columns (people read this way), not alphabetically rows. Like: ``` a d g i b e h j c f ``` Instead of: ``` a b c d e f g h i j ```