Witaj,
Pewnie dałoby się to zrobić ladniej, ale działa :)
class Program
{
static void Main(string[] args)
{
int[] intArray = new int[] { 2, 3, 4, 7, 10, 11, 12 };
int[] intArray1 = new int[] { 2, 3, 4, 7,6, 10, 14, 18 };
int[] intArray2 = new int[] { 2, 3, 4 };
int[] intArray3 = new int[] { 2 };
Console.WriteLine(CreateSections(intArray));
Console.WriteLine(CreateSections(intArray1));
Console.WriteLine(CreateSections(intArray2));
Console.WriteLine(CreateSections(intArray3));
Console.Read();
}
private static string CreateSections(int[] source)
{
if(source == null)
throw new ArgumentNullException("source");
if(source.Length == 0)
return string.Empty;
if (source.Length == 1)
return CreateSingleSection(source[0], source[0]);
var result = new StringBuilder();
int[] orderedSource = source.OrderBy(x=>x).ToArray();
int sectionFrom = orderedSource[0];
int sectionTo = orderedSource[0];
for (int i = 0; i < orderedSource.Length - 1; i++)
{
int value = orderedSource[i];
int nextValue = orderedSource[i + 1];
bool isLastElement = i == orderedSource.Length - 2;
if (isLastElement)
sectionTo = nextValue;
if (!(nextValue == sectionTo + 1) || isLastElement)
{
result.Append(CreateSingleSection(sectionFrom, sectionTo));
sectionFrom = nextValue;
}
sectionTo = nextValue;
}
return result.ToString();
}
private static string CreateSingleSection(int from, int to)
{
if (from == to)
return string.Format("<{0}>", from);
else
return string.Format("<{0},{1}>", from, to);
}
}