Skip to content

Instantly share code, notes, and snippets.

@d-schmidt
Last active May 4, 2021 06:06
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save d-schmidt/cd85136990de250df38956432517b253 to your computer and use it in GitHub Desktop.
Save d-schmidt/cd85136990de250df38956432517b253 to your computer and use it in GitHub Desktop.
Simple golang RangeMap implementation for sorted, not overlapping ranges of integers (like IP address ranges). Elements are found using binary search.
package main
import (
"fmt"
"sort"
)
type Range struct {
L int
U int
}
type RangeMap struct {
Keys []Range
Values []string
}
// works like Guava RangeMap com.google.common.collect.ImmutableRangeMap
// https://github.com/google/guava/blob/1efc5ce983c02cfaa2ce3338bdfaa1f583b66128/guava/src/com/google/common/collect/ImmutableRangeMap.java#L159
func (rm RangeMap) Get(key int) (string, bool) {
i := sort.Search(len(rm.Keys), func(i int) bool {
fmt.Printf("search %v at index %d for %v is %v\n", rm.Keys[i], i, key, key < rm.Keys[i].L)
return key < rm.Keys[i].L
})
i -= 1
if i >= 0 && i < len(rm.Keys) && key <= rm.Keys[i].U {
return rm.Values[i], true
}
return "", false
}
func main() {
rangeMap := RangeMap{ []Range{Range{1,2}, Range{3,4}, Range{6,8}, Range{12,16}, Range{17,18}},
[]string{"a","b","c","d","e"} }
x := 14
value, ok := rangeMap.Get(x)
fmt.Printf("found %v '%s' for %d\n", ok, value, x)
x = 5
value, ok = rangeMap.Get(x)
fmt.Printf("found %v '%s' for %d\n", ok, value, x)
}
// search {6 8} at index 2 for 14 is false
// search {17 18} at index 4 for 14 is true
// search {12 16} at index 3 for 14 is false
// found true 'd' for 14
// search {6 8} at index 2 for 5 is true
// search {3 4} at index 1 for 5 is false
// found false '' for 5
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment