获取地图键之间的所有范围golang



所以我有以下结构,我想迭代FiniteSet,以获得该范围中实际键之间的所有范围。我的意思是得到不包括关键点的范围float64的原因是我也想处理Math.inf()。不过,我不确定这是否是最好的方法。

type (
FiniteSet struct {
set map[float64]nothing
}
nothing struct{}
Range struct {
lowerBoundary float64
upperBoundary float64
}
)

例如

map[float64]nothing {
math.Inf(-1): nothing{},
1: nothing{},
2: nothing{},
5: nothing{},
math.Inf(): nothing{}
}

我希望输出是成品

[]Range {
Range{math.inf(-1), 0}, 
Range{3,4}, 
Range{6, math.Inf()}
}
}

如果不是一团糟的话,我会把我在实现方面的尝试包括在内。我怀疑它不会给这个问题带来任何混乱。

package main
import (
"fmt"
"math"
"sort"
)
type (
FiniteSet struct {
set map[float64]nothing
}
nothing struct{}
Range struct {
lowerBoundary float64
upperBoundary float64
}
)
func main() {
data := map[float64]nothing{
math.Inf(-1): nothing{},
1:            nothing{},
2:            nothing{},
5:            nothing{},
math.Inf(1):  nothing{},
}
r := process(data)
fmt.Printf("%vn", r)
}
func process(data map[float64]nothing) []Range {
keys := make([]float64, 0)
for k := range data {
keys = append(keys, k)
}
sort.Float64s(keys)
r := make([]Range, 0)
for i := 0; i < len(keys)-1; i++ {
if 1 == keys[i+1]-keys[i] {
continue
}
var current Range
if keys[i] == math.Inf(-1) {
current.lowerBoundary = keys[i]
} else {
current.lowerBoundary = keys[i] + 1
}
if keys[i+1] == math.Inf(1) {
current.upperBoundary = keys[i+1]
} else {
current.upperBoundary = keys[i+1] - 1
}
r = append(r, current)
}
return r
}

最新更新