plar / go-adaptive-radix-tree

Adaptive Radix Trees implemented in Go

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

LongestPrefix

derkan opened this issue · comments

Hi,

Is it possible to add func to find the longest common prefix match?

Thanks

Having following keys:

343
3435
3432

Calling LongestPrefix should give us:

t.LongestPrefix('34353212') => 3435
t.LongestPrefix('34312345') => 343

I think a similar question was asked in #11 with some interesting ideas therein...

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.