Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Package bench is a package which contains
- // programs of Go Benchmark Competition.
- package bench
- import (
- "bufio"
- "bytes"
- "errors"
- "fmt"
- "io"
- "os"
- "strings"
- )
- // 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.
- // Methods:
- // BenchmarkFind 30000 41445 ns/op (Mon Mar 23 14:10:47 CET 2015)
- // BenchmarkFind 50000 28312 ns/op (Mon Mar 23 19:26:33 CET 2015)
- func Find(path, word string) (string, error) {
- if len(word) == 0 {
- return "", errors.New("word cannot be empty")
- }
- file, _ := os.Open(path)
- defer file.Close()
- reader := bufio.NewReader(file)
- var found []string
- var row int
- for {
- offset := 0
- line, err := reader.ReadSlice(0x0a)
- if err == io.EOF {
- break
- }
- row++
- for {
- index := bytes.Index(line, []byte(word))
- offset = offset + index
- if index != -1 && offset < len(line) {
- found = append(found, fmt.Sprintf("%d:%d", row, offset))
- offset++
- line = line[offset:]
- } else {
- break
- }
- }
- }
- return strings.Join(found, ","), nil
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement