LongestPrefix
derkan opened this issue · comments
Erkan Durmuş commented
Hi,
Is it possible to add func to find the longest common prefix match?
Thanks
Pavel Larkin commented
Can you provide a code example/test about what you really want to do?
…On Tue, Nov 17, 2020, 07:56 Erkan Durmuş ***@***.***> wrote:
Hi,
Is it possible to add func to find the longest common prefix match?
Thanks
—
You are receiving this because you are subscribed to this thread.
Reply to this email directly, view it on GitHub
<#19>, or unsubscribe
<https://github.com/notifications/unsubscribe-auth/AAARYI55TZ2XTH7K6THSRRTSQKMLFANCNFSM4TYYFB4Q>
.
Erkan Durmuş commented
Having following keys:
343
3435
3432
Calling LongestPrefix
should give us:
t.LongestPrefix('34353212')
=> 3435
t.LongestPrefix('34312345')
=> 343
James Mills commented
I think a similar question was asked in #11 with some interesting ideas therein...
Pavel Larkin commented
It is not exactly similar but it also can be implemented quite easily using the existing API (Go Playground).
package main
import (
"github.com/plar/go-adaptive-radix-tree"
"github.com/stretchr/testify/assert"
"testing"
)
func LongestPrefix(tree art.Tree, s string) (lp string) {
for i := len(s); i > 0 && len(lp) == 0; i-- {
p := s[:i]
tree.ForEachPrefix(art.Key(p), func(n art.Node) bool {
lp = string(n.Key()) // only leaf node has Key
return len(lp) == 0 // still empty? continue
})
}
return
}
func TestLongestPrefix(t *testing.T) {
assert := assert.New(t)
tree := art.New()
assert.NotNil(tree)
tree.Insert(art.Key("343"), "343")
tree.Insert(art.Key("3435"), "3435")
tree.Insert(art.Key("3432"), "3432")
assert.Equal("3435", LongestPrefix(tree, "34353212"))
assert.Equal("343", LongestPrefix(tree, "34312345"))
assert.Equal("343", LongestPrefix(tree, "3"))
assert.Equal("", LongestPrefix(tree, "abcd"))
}
I will close this issue as it is quite easy to implement using the existing API.