-
Notifications
You must be signed in to change notification settings - Fork 0
/
tree.go
134 lines (111 loc) · 2.22 KB
/
tree.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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
package platecalc
import (
"fmt"
"math"
"strings"
)
type Tree struct {
Parent *Tree
Depth int
Children map[float32]*Tree
Value float32
}
func NewTree(parent *Tree, value float32) *Tree {
depth := 0
if parent != nil {
depth = parent.Depth + 1
}
return &Tree{
Parent: parent,
Depth: depth,
Children: make(map[float32]*Tree),
Value: value,
}
}
func (t *Tree) Score(preferLessPlates bool) int {
if t.Parent == nil {
return 0
}
var scale float32 = 1
if !preferLessPlates {
// scale up heavier plates; prefer lighter plates
scale = float32(math.Round(float64(t.Value) / 10))
if scale < 1 {
scale = 1
}
}
return t.Parent.Score(preferLessPlates) + t.Depth*int(t.Value*scale)
}
func (t *Tree) TotalWeight() float32 {
if t.Parent == nil {
return t.Value
}
return t.Parent.TotalWeight() + t.Value*2
}
func (t *Tree) Find(plates ...float32) *Tree {
if len(plates) == 0 {
return nil
}
plate, rest := plates[0], plates[1:]
next, ok := t.Children[plate]
if !ok {
return nil
}
if len(rest) > 0 {
return next.Find(rest...)
} else {
return next
}
}
func (t *Tree) Add(plates ...float32) *Tree {
if len(plates) == 0 {
return nil
}
plate, rest := plates[0], plates[1:]
next, ok := t.Children[plate]
if !ok {
next = NewTree(t, plate)
t.Children[plate] = next
}
if len(rest) > 0 {
return next.Add(rest...)
} else {
return next
}
}
type WalkTreeFn func(*Tree)
func (t *Tree) Walk(fn WalkTreeFn) {
fn(t)
for _, child := range t.Children {
child.Walk(fn)
}
}
type WalkNearbyTreeFn func(*Tree, int)
func (t *Tree) WalkNearby(maxDistance int, fn WalkNearbyTreeFn) {
seen := make(map[*Tree]bool)
var walk func(*Tree, int)
walk = func(t *Tree, distance int) {
if t == nil || distance > maxDistance {
return
}
if _, ok := seen[t]; ok {
return
}
fn(t, distance)
seen[t] = true
for _, child := range t.Children {
walk(child, distance+1)
}
walk(t.Parent, distance+1)
}
walk(t, 0)
}
func (t *Tree) String() string {
plates := make([]string, 0)
for parent := t; parent != nil; parent = parent.Parent {
if parent.Parent != nil {
plates = append([]string{fmt.Sprintf("%v", parent.Value)}, plates...)
}
}
return strings.Join(plates, ", ")
}