code.go 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  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. cost int
  50. }
  51. func buildGraph(valves map[string]valve) []path {
  52. var graph []path
  53. for key, value := range valves {
  54. for i := range value.connections {
  55. graph = append(graph, path{key, value.connections[i], 1})
  56. }
  57. }
  58. return graph
  59. }
  60. func main() {
  61. if len(os.Args) < 2 {
  62. log.Fatal("You need to specify a file!")
  63. }
  64. filePath := os.Args[1]
  65. file, err := os.Open(filePath)
  66. if err != nil {
  67. log.Fatalf("Failed to open %s!\n", filePath)
  68. }
  69. valves := readInput(file)
  70. graph := buildGraph(valves)
  71. fmt.Println(graph)
  72. }