Assume I have the following list (List<string>
)
G
G
M
T
I'd like this to be in an order where the same letter will not occur twice, such as
G
M
G
T
(I appreciate other variations would also suffice)
Please note, if I had the following
G
G
G
G
G
M
T
Then of course some values will have to occur concurrently. The position within the List where this concurrency occurs is not relevant. What I'm after is to stop this repetition where possible to most evenly spread the letters.
The C# console application code I share works
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace resorting
{
class Program
{
static void Main(string[] args)
{
List<string> list = new List<string> { "G", "G", "G", "G", "M", "M", "T", "T", "T", "T", "T", "T", "T", "T", "G", "G", "G", "G", "M", "M", "T", "T", "T", "T", "T", "T", "T", "T" };
list.UpdateList();
}
}
public static class extension
{
public static void UpdateList(this List<string> list)
{
GetList(list);
list.Reverse(); // DO I HAVE TO REVERSE
GetList(list); // AND THEN CALL THE METHOD AGAIN
}
private static void GetList(List<string> list)
{
int total = list.Count;
int inc = 2;
for (int i = 0; i < total; i++)
{
if (total <= i + 2)
break;
if (total <= i + inc)
continue;
if (list[i] == list[i + 1])
{
var val = list[i];
list.RemoveAt(i);
list.Insert(i + inc, val);
i = i - 1;
inc++;
continue;
}
inc = 2;
}
}
}
}
As you can see, I have to call this function twice. I reverse the order and then reapply the same logic. Whilst it works, and based upon the amount of data I will be using, I don't need the function to be more efficient my question is still about efficiency (if worth while against the amount of work required).
Can I update the code to not need to reverse the list to avoid calling the code twice?