我需要編寫一個代碼,其中包含Groovy中的一系列範圍。我需要創建一個新的列表,所有的範圍不重疊。刪除範圍列表中的重疊範圍Groovy
例如,如果輸入是:[13..15,14..16]
我應該能夠創建具有任一[13..16]或[13..14列表, 14..16]
我真的很感激任何幫助。我寫了下面的代碼,但現在它不工作一個位:
def removeOverlapInRanges(ranges)
{
def cleanedRanges = []
def overLapFound = false
def rangeIsClean = true
def test = "ranges"
ranges.each
{
range->
def index = ranges.indexOf(range)
while (index < ranges.size() -1)
{
if (ranges.get(index + 1).disjoint(range) == false)
{
overLapFound = true
rangeIsClean = false
def nextRange = ranges.get(index + 1)
if (range.from > nextRange.from && range.to < nextRange.to)
cleanedRanges.add(range.from..range.to)
else if (range.from < nextRange.from && range.to < nextRange.to)
cleanedRanges.add(range.from..nextRange.to)
else if (range.from > nextRange.from && range.to > nextRange.to)
cleanedRanges.add(nextRange.from..range.to)
}
index = index + 1
}
if (rangeIsClean)
cleanedRanges.add(range)
rangeIsClean = true
test = test + cleanedRanges
}
cleanedRanges.add(0, cleanedRanges.get(cleanedRanges.size()-1))
cleanedRanges.remove(cleanedRanges.size() - 1)
if (overLapFound)
return removeOverlapInRanges(cleanedRanges)
else
return cleanedRanges
}
我通過[12..13,17..19,18..22,17..19,22..23, 19..20]
作爲回報我事先的任何輸入了[12..13]
謝謝!
謝謝您的輸入.. – user2119516 2013-03-07 08:34:10