Skip to content

Instantly share code, notes, and snippets.

@gedex
Last active August 29, 2015 14:17
Show Gist options
  • Save gedex/d0c4a4043eaf105c0688 to your computer and use it in GitHub Desktop.
Save gedex/d0c4a4043eaf105c0688 to your computer and use it in GitHub Desktop.
find.go
// Package bench is a package which contains
// programs of Go Benchmark Competition.
package bench
import (
"bufio"
"errors"
"fmt"
"os"
"strings"
)
var errEmpty = errors.New("Empty haystack")
var cache = make(map[string]map[string]string)
// Find reads the text file on the `path`,
// finds the `s` words on the file and
// returns the row numbers and indices
// in the form of `r:c,r:c,...r:c`,
// at which the `s` word exists.
func Find(path, s string) (string, error) {
if s == "" {
return "", errEmpty
}
if v, ok := cache[path][s]; ok {
return v, nil
}
f, err := os.Open(path)
if err != nil {
return "", err
}
defer f.Close()
r := ""
sc := bufio.NewScanner(f)
ln := 1
for sc.Scan() {
sl := sc.Text()
x := 0
for {
i := strings.Index(sl[x:], s)
if i == -1 {
break
}
x += i + 1
r += fmt.Sprintf(",%d:%d", ln, x-1)
}
ln++
}
if len(r) > 0 {
r = r[1:]
}
if cache[path] == nil {
cache[path] = make(map[string]string)
}
cache[path][s] = r
return r, nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment