code.go 1.8 KB

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