//它是用C#语言编写的。但是概念可以用任何编程语言来实现。
public class Range
{
public int startNo { get; set; }
public int stopNo { get; set; }
public Range(int start, int stop)
{
startNo = start;
stopNo = stop;
}
}
public void GetUniqueRanges()
{
var rangeList = new List<Range>();
rangeList.Add(new Range(7,4));
rangeList.Add(new Range(3, 15));
rangeList.Add(new Range(54, 35));
rangeList.Add(new Range(45, 60));
rangeList.Add(new Range(60,75));
rangeList.Add(new Range(76,100));
rangeList.Add(new Range(6,10));
rangeList.Add(new Range(16,24));
rangeList.Add(new Range(19,34));
var sorted = new List<Range>();
foreach (var range in rangeList)
{
var item = new Range(Math.Min(range.startNo, range.stopNo), Math.Max(range.startNo, range.stopNo));
sorted.Add(item);
}
var result = new List<Range>();
sorted = sorted.OrderBy(x => x.startNo).ToList();
var counter = sorted.Count;
for (var i = 0; i < counter; )
{
var item = new Range (sorted[i].startNo, sorted[i].stopNo );
var j = i + 1;
for (; j < counter; j++)
{
if (sorted[j].startNo <= item.stopNo)
{
item.stopNo =Math.Max(item.stopNo, sorted[j].stopNo);
}
else
{
break;
}
}
i = j;
result.Add(item);
}
}