Convert integer sets to ranges using C #

What is the most idiomatic way to convert a set of integers to a set of ranges?

eg. given the set of {0, 1, 2, 3, 4, 7, 8, 9, 11} I want to get {{0,4}, {7,9}, {11,11}} using C #

This question has already been answered in C ++ @ Solution in C ++

+7
c # algorithm
source share
3 answers

This is not very effective, but it is idiomatic:

var nums = new HashSet<int>{0, 1, 2, 3, 4, 7, 8, 9, 11}; IEnumerable<Tuple<int, int>> ranges = Enumerable.Zip( nums.Where(n => !nums.Contains(n - 1)), nums.Where(n => !nums.Contains(n + 1)), Tuple.Create); 

More efficient if it is sorted:

 public IEnumerable<Tuple<int, int>> GetContiguousRanges(IEnumerable<int> nums) { int start = nums.First(); int last = start - 1; foreach (int i in nums) { if (i != last + 1) { yield return Tuple.Create(start, last); start = i; } last = i; } yield return Tuple.Create(start, last); } 
+10
source share

This should be a fairly simple transliteration from the message you mentioned. Make sure you put this code in the class somewhere, C # code must be in the class. I assume that you are not very familiar with C #, so I will do enough to show the similarities and differences, and I hope you can handle the rest.

 struct Range { public Range (int start, int end) { this.start = start; this.end = end; } public int start; public int end; } public static void SetToRanges(Dictionary<int,bool> indices, List<Range> ranges) { Range r = new Range(int.MinValue, int.MaxValue); foreach (int i in indices.Keys) { // translate rest of code here } ranges.Add(r); return ranges; } 

For a more idiomatic soluiton, I would return an IEnumerable<Range> , so a list can be created and repeated at the same time:

 public static IEnumerable<Range> SetToRanges(Dictionary<int, bool> indices) { // instead of "ranges.Add(r)", use "yield return r". // This returns multiple values in order from the function, that can // be iterated with "foreach (Range i in SetToRanges(foo))" } 
+3
source share

Try K-type clustering to get ranges. You need to specify how many different ranges you want.

-one
source share

All Articles