code.go 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. package main
  2. import (
  3. "bufio"
  4. "fmt"
  5. "log"
  6. "os"
  7. "strings"
  8. )
  9. type Cube struct {
  10. count int
  11. color string
  12. }
  13. type Game struct {
  14. id int
  15. sets [][]Cube
  16. }
  17. func readInput(file *os.File) []Game {
  18. scanner := bufio.NewScanner(file)
  19. var games []Game
  20. for scanner.Scan() {
  21. line := scanner.Text()
  22. if line == "" {
  23. break
  24. }
  25. var current Game
  26. n, err := fmt.Sscanf(line, "Game %d:", &current.id)
  27. if n != 1 || err != nil {
  28. log.Fatalf("Failed to read game: %s\n%s", line, err)
  29. }
  30. gameParts := strings.Split(line, ":")
  31. if len(gameParts) != 2 {
  32. log.Fatalf("Wrong input: %s", line)
  33. }
  34. sets := strings.Split(gameParts[1], ";")
  35. if len(sets) == 0 {
  36. log.Fatalf("Wrong input: %s", gameParts[1])
  37. }
  38. for i := range sets {
  39. var set []Cube
  40. cubes := strings.Split(sets[i], ",")
  41. if len(cubes) == 0 {
  42. log.Fatalf("Wrong input: %s", sets[i])
  43. }
  44. for j := range cubes {
  45. var cube Cube
  46. n, err = fmt.Sscanf(cubes[j], "%d %s", &cube.count, &cube.color)
  47. if n != 2 || err != nil {
  48. log.Fatalf("Wrong input: %s\n%s", cubes[j], err)
  49. }
  50. set = append(set, cube)
  51. }
  52. current.sets = append(current.sets, set)
  53. }
  54. games = append(games, current)
  55. }
  56. return games
  57. }
  58. func main() {
  59. if len(os.Args) < 2 {
  60. log.Fatal("You need to specify a file!")
  61. }
  62. filePath := os.Args[1]
  63. file, err := os.Open(filePath)
  64. if err != nil {
  65. log.Fatalf("Failed to open %s!\n", filePath)
  66. }
  67. games := readInput(file)
  68. fmt.Println(games)
  69. }