forked from cybrota/recaller
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathavl_tree.go
More file actions
384 lines (318 loc) · 9.44 KB
/
Copy pathavl_tree.go
File metadata and controls
384 lines (318 loc) · 9.44 KB
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
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
// Copyright 2025 Naren Yellavula
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package main
import (
"sort"
"strings"
"time"
)
type CommandMetadata struct {
Command string
Timestamp *time.Time // Unix timestamp for recency (updated on each use)
Frequency int // Incremented on each command execution
}
type RankedCommand struct {
Command string
Score float64
Metadata CommandMetadata
}
type AVLNode struct {
Key string // Command (e.g., "echo Hello, World!")
Value CommandMetadata // Associated data (e.g., timestamp)
Height int
Left *AVLNode
Right *AVLNode
}
type AVLTreeIFace interface {
Insert(key string, value interface{})
Delete(key string)
Search(key string) (interface{}, bool)
SearchPrefix(prefix string) []*AVLNode
SearchFuzzy(query string) []*AVLNode
SearchPrefixMostRecent(prefix string) []*AVLNode
}
type AVLTree struct {
Root *AVLNode
}
func NewAVLTree() *AVLTree {
return &AVLTree{Root: nil}
}
func (tree *AVLTree) getHeight(node *AVLNode) int {
if node == nil {
return 0
}
return node.Height
}
func (tree *AVLTree) updateHeight(node *AVLNode) {
node.Height = max(tree.getHeight(node.Left), tree.getHeight(node.Right)) + 1
}
func (tree *AVLTree) getBalanceFactor(node *AVLNode) int {
if node == nil {
return 0
}
return tree.getHeight(node.Left) - tree.getHeight(node.Right)
}
func (tree *AVLTree) rotateLeft(node *AVLNode) *AVLNode {
// Check if input node is valid
if node == nil || node.Right == nil {
return node // Nothing to rotate or invalid input
}
// Identify the pivot node (new root)
pivot := node.Right
// Perform the rotation
node.Right = pivot.Left
pivot.Left = node
// Update heights
tree.updateHeight(node)
tree.updateHeight(pivot)
return pivot // Return the new root node
}
func (tree *AVLTree) rotateRight(node *AVLNode) *AVLNode {
// Check if input node is valid
if node == nil || node.Left == nil {
return node // Nothing to rotate or invalid input
}
// Identify the pivot node (new root)
pivot := node.Left
// Perform the rotation
node.Left = pivot.Right
pivot.Right = node
// Update heights
tree.updateHeight(node)
tree.updateHeight(pivot)
return pivot // Return the new root node
}
func (tree *AVLTree) Insert(key string, value CommandMetadata) {
tree.Root = tree.insertRecursive(tree.Root, key, value)
}
func (tree *AVLTree) insertRecursive(node *AVLNode, key string, value CommandMetadata) *AVLNode {
if node == nil {
return &AVLNode{Key: key, Value: value, Height: 1}
}
if key < node.Key {
node.Left = tree.insertRecursive(node.Left, key, value)
} else if key > node.Key {
node.Right = tree.insertRecursive(node.Right, key, value)
} else {
// Handle duplicate keys (e.g., update value)
}
tree.updateHeight(node)
balanceFactor := tree.getBalanceFactor(node)
if balanceFactor > 1 {
if key < node.Left.Key {
return tree.rotateRight(node)
} else {
// Left-Right case
node.Left = tree.rotateLeft(node.Left)
return tree.rotateRight(node)
}
} else if balanceFactor < -1 {
if key > node.Right.Key {
return tree.rotateLeft(node)
} else {
// Right-Left case
node.Right = tree.rotateRight(node.Right)
return tree.rotateLeft(node)
}
}
return node
}
func (tree *AVLTree) Delete(key string) {
tree.Root = tree.deleteRecursive(tree.Root, key)
}
func (tree *AVLTree) deleteRecursive(node *AVLNode, key string) *AVLNode {
if node == nil {
return nil // Key not found
}
if key < node.Key {
node.Left = tree.deleteRecursive(node.Left, key)
} else if key > node.Key {
node.Right = tree.deleteRecursive(node.Right, key)
} else { // Found the node to delete
// Case 1: No children
if node.Left == nil && node.Right == nil {
return nil
}
// Case 2: One child (right)
if node.Left == nil {
return node.Right
}
// Case 3: One child (left)
if node.Right == nil {
return node.Left
}
// Case 4: Two children
pivot := tree.findMin(node.Right) // Find the minimum in the right subtree
node.Key = pivot.Key
node.Value = pivot.Value
node.Right = tree.deleteRecursive(node.Right, pivot.Key)
}
// Update height and balance factor after deletion
tree.updateHeight(node)
return tree.rebalance(node)
}
func (tree *AVLTree) findMin(node *AVLNode) *AVLNode {
for node.Left != nil {
node = node.Left
}
return node
}
func (tree *AVLTree) rebalance(node *AVLNode) *AVLNode {
balanceFactor := tree.getBalanceFactor(node)
// Left-heavy
if balanceFactor > 1 {
if tree.getBalanceFactor(node.Left) >= 0 {
return tree.rotateRight(node)
} else {
node.Left = tree.rotateLeft(node.Left)
return tree.rotateRight(node)
}
}
// Right-heavy
if balanceFactor < -1 {
if tree.getBalanceFactor(node.Right) <= 0 {
return tree.rotateLeft(node)
} else {
node.Right = tree.rotateRight(node.Right)
return tree.rotateLeft(node)
}
}
return node
}
// Search looks for the node with the given key in the AVL tree.
// It returns the value if found, and a boolean indicating whether the key was found.
func (tree *AVLTree) Search(key string) (interface{}, bool) {
return searchNode(tree.Root, key)
}
// searchNode is a helper function that traverses the AVL tree recursively.
func searchNode(node *AVLNode, key string) (interface{}, bool) {
if node == nil {
return nil, false
}
if key < node.Key {
return searchNode(node.Left, key)
} else if key > node.Key {
return searchNode(node.Right, key)
} else {
// key == node.Key
return node.Value, true
}
}
// rangeSearch traverses the subtree rooted at 'node' and appends to 'results'
// every node whose Key satisfies low <= Key < high, in ascending (lexicographical) order.
func rangeSearch(node *AVLNode, low, high string, results *[]*AVLNode) {
if node == nil {
return
}
// Use string comparison optimization - only traverse left if needed
if node.Key >= low {
rangeSearch(node.Left, low, high, results)
}
// If node.Key is actually in [low, high), collect it
if len(node.Key) >= len(low) && strings.HasPrefix(node.Key, low) {
*results = append(*results, node)
}
// Use string comparison optimization - only traverse right if needed
if node.Key < high {
rangeSearch(node.Right, low, high, results)
}
}
func (tree *AVLTree) SearchPrefix(prefix string) []*AVLNode {
var results []*AVLNode
// Construct high bound as prefix + "\uffff"
high := prefix + "\uffff"
rangeSearch(tree.Root, prefix, high, &results)
return results
}
func (tree *AVLTree) SearchPrefixMostRecent(prefix string) []*AVLNode {
// 1. Gather prefix matches (keys in [prefix, prefix+"\uffff"))
matches := tree.SearchPrefix(prefix)
sort.Slice(matches, func(i, j int) bool {
// Type assert both sides to *time.Time
t1 := matches[i].Value.Timestamp
t2 := matches[j].Value.Timestamp
if t1 == nil && t2 == nil {
return false
}
if t1 == nil {
// nil is considered older
return false
}
if t2 == nil {
// non-nil is considered newer
return true
}
// Now both t1, t2 are non-nil *time.Time
// Return true if t1 is after t2 => t1 is more recent
return t1.After(*t2)
})
return matches
}
func calculateScore(metadata CommandMetadata) float64 {
frequencyScore := float64(metadata.Frequency)
var recencyScore float64
if metadata.Timestamp != nil && !metadata.Timestamp.IsZero() {
timeDelta := time.Since(*metadata.Timestamp).Hours()
if timeDelta < 0 {
timeDelta = 0
}
recencyScore = 1 / (timeDelta + 1) // Add 1 to avoid division by zero
}
return (0.6 * frequencyScore) + (0.4 * recencyScore)
}
// fuzzySearch performs in-order traversal and finds commands containing the query as substring
func fuzzySearch(node *AVLNode, query string, results *[]*AVLNode) {
if node == nil {
return
}
// Traverse left subtree
fuzzySearch(node.Left, query, results)
// Check if current node contains the query as substring (case-insensitive)
if strings.Contains(strings.ToLower(node.Key), strings.ToLower(query)) {
*results = append(*results, node)
}
// Traverse right subtree
fuzzySearch(node.Right, query, results)
}
func (tree *AVLTree) SearchFuzzy(query string) []*AVLNode {
var results []*AVLNode
fuzzySearch(tree.Root, query, &results)
return results
}
func SearchWithRanking(tree *AVLTree, query string, enableFuzzing bool) []RankedCommand {
var nodes []*AVLNode
if enableFuzzing {
nodes = tree.SearchFuzzy(query)
} else {
nodes = tree.SearchPrefix(query)
}
// Pre-allocate slice with estimated capacity to reduce allocations
rankedCommands := make([]RankedCommand, 0, len(nodes))
// Traverse the tree to find matching commands
for _, node := range nodes {
command := node.Key
metadata := node.Value
rankedCommand := RankedCommand{
Command: command,
Score: calculateScore(metadata),
Metadata: metadata, // Reuse existing metadata to avoid copying
}
rankedCommands = append(rankedCommands, rankedCommand)
}
// Sort the commands based on their scores (Descending order for highest score first)
sort.SliceStable(rankedCommands, func(i, j int) bool {
return rankedCommands[i].Score > rankedCommands[j].Score
})
return rankedCommands
}