code.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. package main
  2. import (
  3. "bufio"
  4. "fmt"
  5. "log"
  6. "os"
  7. "regexp"
  8. "strings"
  9. )
  10. type valve struct {
  11. name string
  12. rate int
  13. open bool
  14. connections []string
  15. }
  16. func readInput(file *os.File) map[string]valve {
  17. scanner := bufio.NewScanner(file)
  18. valves := make(map[string]valve)
  19. for scanner.Scan() {
  20. line := scanner.Text()
  21. if line == "" {
  22. continue
  23. }
  24. var current valve
  25. if strings.Contains(line, "valves") {
  26. n, err := fmt.Sscanf(line, "Valve %s has flow rate=%d", &current.name, &current.rate)
  27. if n != 2 || err != nil {
  28. log.Fatal("Can't parse (valves):", line, err)
  29. }
  30. re := regexp.MustCompile(`valves .*`)
  31. parts := re.FindString(line)
  32. parts = strings.TrimLeft(parts, "valves ")
  33. current.connections = strings.Split(parts, ", ")
  34. } else {
  35. var connection string
  36. n, err := fmt.Sscanf(line, "Valve %s has flow rate=%d; tunnel leads to valve %s", &current.name, &current.rate, &connection)
  37. if n != 3 || err != nil {
  38. log.Fatal("Can't parse:", line, err)
  39. }
  40. current.connections = append(current.connections, connection)
  41. }
  42. valves[current.name] = current
  43. }
  44. return valves
  45. }
  46. type path struct {
  47. from string
  48. to string
  49. }
  50. func buildGraph(valves map[string]valve) []path {
  51. var graph []path
  52. for key, value := range valves {
  53. for i := range value.connections {
  54. graph = append(graph, path{key, value.connections[i]})
  55. }
  56. }
  57. return graph
  58. }
  59. func main() {
  60. if len(os.Args) < 2 {
  61. log.Fatal("You need to specify a file!")
  62. }
  63. filePath := os.Args[1]
  64. file, err := os.Open(filePath)
  65. if err != nil {
  66. log.Fatalf("Failed to open %s!\n", filePath)
  67. }
  68. valves := readInput(file)
  69. graph := buildGraph(valves)
  70. fmt.Println(graph)
  71. }