-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathleaf.go
67 lines (62 loc) · 2.29 KB
/
leaf.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
package main
import "golang.org/x/exp/constraints"
type leaf[T constraints.Ordered] struct {
interval IntervalWithValue[T]
left *leaf[T]
right *leaf[T]
}
func (receiver *leaf[T]) SearchMultipleIntervals(foundIntervals []IntervalWithValue[T], value T, includeInit, includeEnd bool) ([]IntervalWithValue[T], error) {
evaluation := receiver.interval.Evaluate(value, includeInit, includeEnd)
if foundIntervals == nil {
foundIntervals = make([]IntervalWithValue[T], 0)
}
switch evaluation {
case "Under":
if receiver.left != nil {
foundIntervals, _ = receiver.left.SearchMultipleIntervals(foundIntervals, value, includeInit, includeEnd)
}
case "Upper":
if receiver.right != nil {
foundIntervals, _ = receiver.right.SearchMultipleIntervals(foundIntervals, value, includeInit, includeEnd)
}
case "Contained":
foundIntervals = append(foundIntervals, receiver.interval)
if receiver.left != nil {
foundIntervals, _ = receiver.left.SearchMultipleIntervals(foundIntervals, value, includeInit, includeEnd)
}
if receiver.right != nil {
foundIntervals, _ = receiver.right.SearchMultipleIntervals(foundIntervals, value, includeInit, includeEnd)
}
default:
return foundIntervals, nil
}
return foundIntervals, nil
}
func (receiver *leaf[T]) SearchFirstInterval(value T, includeInit, includeEnd bool) (IntervalWithValue[T], error) {
evaluation := receiver.interval.Evaluate(value, includeInit, includeEnd)
switch evaluation {
case "Under":
if receiver.left != nil {
return receiver.left.SearchFirstInterval(value, includeInit, includeEnd)
}
case "Upper":
if receiver.right != nil {
return receiver.right.SearchFirstInterval(value, includeInit, includeEnd)
}
case "Contained":
return receiver.interval, nil
default:
return IntervalWithValue[T]{}, errorEvaluationValueOutOfBounds{value: value, evaluationResult: evaluation}
}
return IntervalWithValue[T]{}, errorEvaluationValueOutOfBounds{value: value, evaluationResult: evaluation}
}
func GenerateLeaf[T constraints.Ordered](sortedIntervals []IntervalWithValue[T], min, max int) *leaf[T] {
if min == max {
return nil
}
half := (min + max) / 2
interval := sortedIntervals[half]
left := GenerateLeaf(sortedIntervals, min, half)
right := GenerateLeaf(sortedIntervals, half+1, max)
return &leaf[T]{interval, left, right}
}