Suffixarray Lookup Repeated Offsets

Index text with index/suffixarray and query it with Lookup and FindAllIndex to collect every occurrence offset of a pattern.

GoData Integrity

Code

gosnippet
27 lines
package main

import (
	"fmt"
	"index/suffixarray"
)

func main() {
	text := []byte("banana bandana ananas")
	index := suffixarray.New(text)

	// Lookup returns every starting offset of the pattern
	offsets := index.Lookup([]byte("ana"), -1)
	fmt.Println("ana offsets:", offsets)
	fmt.Println("ana count:", len(offsets))

	// a negative limit means no limit, a positive one caps the result
	capped := index.Lookup([]byte("an"), 3)
	fmt.Println("first three an:", capped)

	// FindAllIndex returns [start, end] pairs instead of start offsets
	spans := index.FindAllIndex([]byte("band"), -1)
	fmt.Println("band spans:", spans)

	// a missing pattern produces an empty result rather than an error
	fmt.Println("missing:", index.Lookup([]byte("kiwi"), -1))
}

How the snippet works

Under the hood: the function main.

Points of care

  • Built-in APIs only, so there is no supply chain to vet.

Using it

The demo output is labeled (ana offsets:, ana count:, first three an:), so each line traces straight back to the statement that printed it.

Key statements

spans := index.FindAllIndex([]byte("band"), -1)

Interactive Tools for This Topic

FAQ

What does Suffixarray Lookup Repeated Offsets print when run?
No setup needed: run the file and look for labeled lines like `ana offsets:`, `ana count:`, `first three an:` in the output.