code.go 4.6 KB

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