Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dividing items into columns

Tags:

c#

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
like image 712
user1330271 Avatar asked Jan 26 '26 10:01

user1330271


2 Answers

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

like image 133
yamen Avatar answered Jan 28 '26 23:01

yamen


Just loop over the array distributing the array items with a few if statements within it.

int j = 0;

for (int i = 0; i < s.Length; i++)
{
    if (j == 0)
      // put s[i] in column 1 j = j +1
    else if (j == 1)
      // put s[i] in column 2 j = j +1
    else if (j == 2)
      // put s[i] in column 3 j = j +1
    if (j == 3)
      // put s[i] in column 4 set j = 0
}
like image 40
evanmcdonnal Avatar answered Jan 28 '26 22:01

evanmcdonnal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!