Advertisement
Guest User

Untitled

a guest
May 7th, 2015
251
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.11 KB | None | 0 0
  1. // Package bench is a package which contains
  2. // programs of Go Benchmark Competition.
  3. package bench
  4.  
  5. import (
  6. "bufio"
  7. "bytes"
  8. "errors"
  9. "fmt"
  10. "io"
  11. "os"
  12. "strings"
  13. )
  14.  
  15. // Find reads the text file on the `path`,
  16. // finds the `s` words on the file and
  17. // returns the row numbers and indices
  18. // in the form of `r:c,r:c,...r:c`,
  19. // at which the `s` word exists.
  20.  
  21. // Methods:
  22. // BenchmarkFind 30000 41445 ns/op (Mon Mar 23 14:10:47 CET 2015)
  23. // BenchmarkFind 50000 28312 ns/op (Mon Mar 23 19:26:33 CET 2015)
  24. func Find(path, word string) (string, error) {
  25. if len(word) == 0 {
  26. return "", errors.New("word cannot be empty")
  27. }
  28.  
  29. file, _ := os.Open(path)
  30. defer file.Close()
  31.  
  32. reader := bufio.NewReader(file)
  33.  
  34. var found []string
  35. var row int
  36.  
  37. for {
  38. offset := 0
  39. line, err := reader.ReadSlice(0x0a)
  40. if err == io.EOF {
  41. break
  42. }
  43.  
  44. row++
  45.  
  46. for {
  47. index := bytes.Index(line, []byte(word))
  48. offset = offset + index
  49. if index != -1 && offset < len(line) {
  50. found = append(found, fmt.Sprintf("%d:%d", row, offset))
  51. offset++
  52. line = line[offset:]
  53. } else {
  54. break
  55. }
  56. }
  57. }
  58.  
  59. return strings.Join(found, ","), nil
  60. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement