intervals/overlap.go
2018-05-29 16:08:17 +02:00

66 lines
1.8 KiB
Go

package interval
import "math"
func (intvls *intervals) HasOverlapped() bool {
intvls.Overlapped()
if intvls.OverlappedList != nil && len(intvls.OverlappedList) > 0 {
return true
}
return false
}
func (intvls *intervals) Overlapped() []*Interval {
if intvls.OverlappedList == nil {
intvls.OverlappedList = intvls.calculateOverlapped()
}
return intvls.OverlappedList
}
func (intvls *intervals) calculateOverlapped() []*Interval {
list := []*Interval{}
if len(intvls.Intervals) == 0 {
return list
}
// sort intervals (if necessary)
intvls.Sort()
lastMinLow := math.MaxInt64
lastMaxHigh := math.MinInt64
for i, intvl := range intvls.Intervals {
// convert if necessary exclusive low/high values into inclusive ones
low, high := intvls.getInclusives(intvl.Low, intvl.High)
// for the first iteration make no sense those operations
if i > 0 {
// check if the front or back side of the current segment overlaps with the previous one
lowInBetween := isLowInBetweenInclusive(lastMinLow, lastMaxHigh, low, high)
highInBetween := isHighInBetweenInclusive(lastMinLow, lastMaxHigh, low, high)
if lowInBetween || highInBetween {
// extract which part is overlapped, create a new interval and add it to the list
biggestLow := max(low, lastMinLow)
smallestHigh := min(high, lastMaxHigh)
list = append(list, &Interval{Low: biggestLow, High: smallestHigh})
}
}
// update control variables (if necessary)
if low < lastMinLow {
lastMinLow = low
}
if high > lastMaxHigh {
lastMaxHigh = high
}
}
return list
}
func (intvls *intervals) valueIsOverlapping(value int, overlapped []*Interval) bool {
for _, ovrlp := range overlapped {
if inBetween(value, ovrlp.Low, ovrlp.High, intvls.LowInclusive, intvls.HighInclusive) {
return true
}
}
return false
}