code.go 858 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. package main
  2. import (
  3. "bufio"
  4. "fmt"
  5. "log"
  6. "os"
  7. "strings"
  8. )
  9. type Dig struct {
  10. direction string
  11. length int
  12. color string
  13. }
  14. func readInput(file *os.File) []Dig {
  15. scanner := bufio.NewScanner(file)
  16. var plan []Dig
  17. for scanner.Scan() {
  18. line := scanner.Text()
  19. if line == "" {
  20. break
  21. }
  22. var current Dig
  23. n, err := fmt.Sscanf(line, "%s %d %s", &current.direction, &current.length, &current.color)
  24. if n != 3 || err != nil {
  25. log.Fatalf("Wrong input: %s\n%s", line, err)
  26. }
  27. current.color = strings.Trim(current.color, "()")
  28. plan = append(plan, current)
  29. }
  30. return plan
  31. }
  32. func main() {
  33. if len(os.Args) < 2 {
  34. log.Fatal("You need to specify a file!")
  35. }
  36. filePath := os.Args[1]
  37. file, err := os.Open(filePath)
  38. if err != nil {
  39. log.Fatalf("Failed to open %s!\n", filePath)
  40. }
  41. plan := readInput(file)
  42. fmt.Println(plan)
  43. }