Fallout 3 and Fallout: New Vegas hacker assistant
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

68 lines
1.3KB

  1. package main
  2. import (
  3. "bufio"
  4. "fmt"
  5. "io"
  6. "regexp"
  7. "strconv"
  8. )
  9. var (
  10. re = regexp.MustCompile("([[:alpha:]]+)[[:space:]]*([[:digit:]]*)")
  11. ErrNoGuesses = fmt.Errorf("No guesses in input")
  12. ErrNotSameLength = fmt.Errorf("Words are not of the same length")
  13. ErrBlankLine = fmt.Errorf("Blank line")
  14. )
  15. func parseGuess(line string) (*Guess, error) {
  16. matches := re.FindStringSubmatch(line)
  17. if len(matches) < 2 {
  18. return nil, ErrBlankLine
  19. }
  20. word := matches[1]
  21. countString := matches[2]
  22. guess := Guess{Word: word}
  23. if len(countString) > 0 {
  24. c, err := strconv.ParseUint(countString, 10, 0)
  25. if err != nil {
  26. return nil, err
  27. }
  28. count := uint(c)
  29. guess.CorrectCount = &count
  30. }
  31. return &guess, nil
  32. }
  33. func parseGuesses(reader io.Reader) ([]Guess, error) {
  34. guesses := []Guess{}
  35. scanner := bufio.NewScanner(reader)
  36. for scanner.Scan() {
  37. line := scanner.Text()
  38. guess, err := parseGuess(line)
  39. if err != nil {
  40. return nil, err
  41. }
  42. guesses = append(guesses, *guess)
  43. }
  44. if len(guesses) == 0 {
  45. return nil, ErrNoGuesses
  46. }
  47. err := checkSameLength(guesses)
  48. if err != nil {
  49. return nil, err
  50. }
  51. return guesses, nil
  52. }
  53. func checkSameLength(guesses []Guess) error {
  54. length := len(guesses[0].Word)
  55. for _, guess := range guesses {
  56. if len(guess.Word) != length {
  57. return ErrNotSameLength
  58. }
  59. }
  60. return nil
  61. }