day13.go 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. package main
  2. import (
  3. "bufio"
  4. "fmt"
  5. "log"
  6. "os"
  7. "strconv"
  8. "strings"
  9. )
  10. type schedule struct {
  11. timestamp int64
  12. buses map[int64]int64
  13. }
  14. func getIDs(busesString string) (map[int64]int64, error) {
  15. buses := make(map[int64]int64)
  16. for _, bus := range strings.Split(busesString, ",") {
  17. if bus == "x" {
  18. continue
  19. }
  20. busID, err := strconv.ParseInt(bus, 10, 32)
  21. if err != nil {
  22. return buses, fmt.Errorf("Error parsing busID %s: %s", bus, err)
  23. }
  24. buses[busID] = 0
  25. }
  26. return buses, nil
  27. }
  28. func readData(file *os.File) (schedule, error) {
  29. scanner := bufio.NewScanner(file)
  30. data := schedule{}
  31. if !scanner.Scan() {
  32. return data, fmt.Errorf("Error reading timestamp!")
  33. }
  34. timestampString := scanner.Text()
  35. timestamp, err := strconv.ParseInt(timestampString, 10, 32)
  36. if err != nil {
  37. return data, fmt.Errorf("Error parsing timestamp %s: %s", timestampString, err)
  38. }
  39. data.timestamp = timestamp
  40. if !scanner.Scan() {
  41. return data, fmt.Errorf("Error reading buses!")
  42. }
  43. busesString := scanner.Text()
  44. if err := scanner.Err(); err != nil {
  45. return data, err
  46. }
  47. data.buses, err = getIDs(busesString)
  48. if err != nil {
  49. return data, err
  50. }
  51. return data, nil
  52. }
  53. func main() {
  54. if len(os.Args) < 2 {
  55. log.Fatal("You need to specify a file!")
  56. }
  57. file, err := os.Open(os.Args[1])
  58. if err != nil {
  59. log.Fatalf("Failed to open %s!\n", os.Args[1])
  60. }
  61. data, err := readData(file)
  62. if err != nil {
  63. log.Fatalf("Failed to read data: %s\n", err)
  64. }
  65. fmt.Println(data)
  66. }