saturn
saturn

Reputation: 171

Interval representation of an integer set c#

This is an assignment that I've been given, it says that if an hash-set contains the values {12, 13, 14, 23, 88, 89, 90, 91} then they would be represented as the set of intervals { [12..14], [23..23], [88..91]}.

Now to the question, should I use for-each for this? I'm kind of confused since I'm not sure if you could group several intervals into 1 set, or should there be different hash-sets?

I did look into some methods like group-by but i don't know if its the right one to use.

Advice or hints are appreciated!

Upvotes: 1

Views: 1161

Answers (1)

CodesInChaos
CodesInChaos

Reputation: 108800

I'd first sort them, and then iterate that ordered set, and combine elements, as long as the difference is only one.

IEnumerable<Tuple<int,int>> GetIntervals(IEnumerable<int> seq)
{
    var orderedSet=seq.OrderBy(i=>i);
    bool first=true;
    int startOfInterval=0,endOfInterval=0;
    foreach(var element in orderedSet)
    {
      if(first)
      {
        startOfInterval=element;
        endOfInterval=element;
        first=false;
      }
      else
      {
        if(element==endOfInterval+1)
          endOfInterval=element;
        else
        {            
          yield return Tuple.Create(startOfInterval, endOfInterval);
          startOfInterval=element;
          endOfInterval=element;
        } 
      }
    }
    yield return Tuple.Create(startOfInterval, endOfInterval);
}

void Main()
{
  var input=new int[]{12, 13, 14, 23, 88, 89, 90, 91};
  GetIntervals(input).Dump();
}

Note that this requires distinct elements in the input. If the input is a hashset, that's guaranteed. Else throw in a Distict() call before calling OrderBy.

Upvotes: 2

Related Questions