code.go 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227
  1. package main
  2. import (
  3. "bufio"
  4. "fmt"
  5. "log"
  6. "os"
  7. "regexp"
  8. "sort"
  9. "strings"
  10. )
  11. type valve struct {
  12. name string
  13. rate int
  14. open bool
  15. connections []string
  16. }
  17. type vertex struct {
  18. name string
  19. cost int
  20. visited bool
  21. }
  22. const maxValue int = 100000
  23. func readInput(file *os.File) ([]vertex, map[string]valve) {
  24. scanner := bufio.NewScanner(file)
  25. valves := make(map[string]valve)
  26. var vertices []vertex
  27. for scanner.Scan() {
  28. line := scanner.Text()
  29. if line == "" {
  30. continue
  31. }
  32. var current valve
  33. if strings.Contains(line, "valves") {
  34. n, err := fmt.Sscanf(line, "Valve %s has flow rate=%d", &current.name, &current.rate)
  35. if n != 2 || err != nil {
  36. log.Fatal("Can't parse (valves):", line, err)
  37. }
  38. re := regexp.MustCompile(`valves .*`)
  39. parts := re.FindString(line)
  40. parts = strings.TrimLeft(parts, "valves ")
  41. current.connections = strings.Split(parts, ", ")
  42. } else {
  43. var connection string
  44. n, err := fmt.Sscanf(line, "Valve %s has flow rate=%d; tunnel leads to valve %s", &current.name, &current.rate, &connection)
  45. if n != 3 || err != nil {
  46. log.Fatal("Can't parse:", line, err)
  47. }
  48. current.connections = append(current.connections, connection)
  49. }
  50. vertices = append(vertices, vertex{current.name, maxValue, false})
  51. valves[current.name] = current
  52. }
  53. return vertices, valves
  54. }
  55. type path struct {
  56. from string
  57. to string
  58. cost int
  59. }
  60. func buildGraph(valves map[string]valve) []path {
  61. var graph []path
  62. for key, value := range valves {
  63. for i := range value.connections {
  64. graph = append(graph, path{key, value.connections[i], 1})
  65. }
  66. }
  67. return graph
  68. }
  69. func setCost(name string, cost int, vertices []vertex) {
  70. for i := range vertices {
  71. if vertices[i].name == name {
  72. vertices[i].cost = cost
  73. break
  74. }
  75. }
  76. }
  77. func getCost(name string, vertices []vertex) int {
  78. for i := range vertices {
  79. if vertices[i].name == name {
  80. return vertices[i].cost
  81. }
  82. }
  83. return 0
  84. }
  85. func getNext(vertices []vertex) *vertex {
  86. min := maxValue
  87. var current *vertex
  88. for i := range vertices {
  89. if vertices[i].visited {
  90. continue
  91. }
  92. if vertices[i].cost <= min {
  93. min = vertices[i].cost
  94. current = &vertices[i]
  95. }
  96. }
  97. return current
  98. }
  99. func traverse(from vertex, vertices []vertex, graph []path) []vertex {
  100. newVertices := make([]vertex, len(vertices))
  101. copy(newVertices, vertices)
  102. current := &vertex{from.name, 0, false}
  103. for {
  104. for j := range graph {
  105. if graph[j].from != current.name {
  106. continue
  107. }
  108. var tentativeCost int
  109. if current.cost == maxValue {
  110. tentativeCost = maxValue
  111. } else {
  112. tentativeCost = current.cost + 1
  113. }
  114. if tentativeCost < getCost(graph[j].to, newVertices) {
  115. setCost(graph[j].to, tentativeCost, newVertices)
  116. }
  117. }
  118. current.visited = true
  119. current = getNext(newVertices)
  120. if current == nil {
  121. break
  122. }
  123. }
  124. return newVertices
  125. }
  126. func filter(vertices []vertex, valves map[string]valve) []vertex {
  127. var result []vertex
  128. for i := range vertices {
  129. val, _ := valves[vertices[i].name]
  130. if !val.open && val.rate > 0 {
  131. result = append(result, vertices[i])
  132. }
  133. }
  134. return result
  135. }
  136. func moveTo(vertices []vertex, valves map[string]valve) *vertex {
  137. filtered := filter(vertices, valves)
  138. if len(filtered) == 0 {
  139. return nil
  140. }
  141. sort.Slice(filtered, func(i, j int) bool {
  142. return valves[filtered[i].name].rate-filtered[i].cost > valves[filtered[j].name].rate-filtered[j].cost
  143. })
  144. return &filtered[0]
  145. }
  146. func part1(vertices []vertex, graph []path, valves map[string]valve) int {
  147. count := 0
  148. rate := 0
  149. current := &vertices[0]
  150. limit := 30
  151. for {
  152. if count >= limit {
  153. break
  154. }
  155. val, _ := valves[current.name]
  156. if !val.open && val.rate > 0 {
  157. count++
  158. val.open = true
  159. rate += (limit - count) * val.rate
  160. valves[current.name] = val
  161. fmt.Println(current, count)
  162. }
  163. canGo := traverse(*current, vertices, graph)
  164. current = moveTo(canGo, valves)
  165. if current == nil {
  166. break
  167. }
  168. count += current.cost
  169. }
  170. return rate
  171. }
  172. func main() {
  173. if len(os.Args) < 2 {
  174. log.Fatal("You need to specify a file!")
  175. }
  176. filePath := os.Args[1]
  177. file, err := os.Open(filePath)
  178. if err != nil {
  179. log.Fatalf("Failed to open %s!\n", filePath)
  180. }
  181. vertices, valves := readInput(file)
  182. graph := buildGraph(valves)
  183. fmt.Println("Part1:", part1(vertices, graph, valves))
  184. }