Zamiana listy na przedziały

0

Witam,
mam następujący problem (pewnie banalny, ale nie wiem jak go ugryźć).
Mam listę, a w niej liczby typu int.
Np. [2, 3, 4, 7, 10, 11, 12]
Chcę ją tak przerobić, aby otrzymać stringa z przedziałami, a mianowicie np.:
"<2-4>, <7>, <10-12>"

Będę wdzięczny za każdą pomoc :)

0

Powiedzmy, że masz pierwszy przedział 1-4 to wyszukujesz liczby z tego przedziału i dodajesz do stringa w postaci <{0}-{1}> itd...

0

Nie do końca rozumiem co masz na myśli.

Po prostu chcę przedstawić dany zbiór liczb jako przedziały - nie bardzo widzę w tym wyszukiwania liczb - jak już to usuwanie....

1

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);
    }
  }
0

**Jonathan1500 **- jesteś genialny! Dzięki wielkie! :)

1 użytkowników online, w tym zalogowanych: 0, gości: 1