code.go 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242
  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. paths []vertex
  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 := &from
  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 generatePaths(vertices []vertex, graph []path, valves map[string]valve) {
  127. for key, value := range valves {
  128. value.paths = traverse(vertex{value.name, 0, false}, vertices, graph)
  129. valves[key] = value
  130. }
  131. }
  132. func contains(visited []string, name string) bool {
  133. for i := range visited {
  134. if visited[i] == name {
  135. return true
  136. }
  137. }
  138. return false
  139. }
  140. func filtered(vertices []vertex, valves map[string]valve, visited []string) []vertex {
  141. var result []vertex
  142. for i := range vertices {
  143. if contains(visited, vertices[i].name) {
  144. continue
  145. }
  146. val, _ := valves[vertices[i].name]
  147. if val.rate > 0 {
  148. result = append(result, vertices[i])
  149. }
  150. }
  151. return result
  152. }
  153. func calculate(moveTo []vertex, valves map[string]valve, visited []string, count int, rate int) int {
  154. if count >= 30 || len(moveTo) == 0 {
  155. return rate
  156. }
  157. max := 0
  158. for i := range moveTo {
  159. currentCount := count + moveTo[i].cost + 1
  160. if currentCount > 30 {
  161. continue
  162. }
  163. val, _ := valves[moveTo[i].name]
  164. val.open = true
  165. valves[moveTo[i].name] = val
  166. newVisited := make([]string, len(visited))
  167. copy(newVisited, visited)
  168. newVisited = append(newVisited, moveTo[i].name)
  169. canGo := valves[moveTo[i].name].paths
  170. toCheck := filtered(canGo, valves, newVisited)
  171. result := calculate(toCheck, valves, newVisited, currentCount, rate+(30-currentCount)*val.rate)
  172. if result > max {
  173. max = result
  174. }
  175. }
  176. return max
  177. }
  178. func part1(from vertex, valves map[string]valve) int {
  179. canGo := valves[from.name].paths
  180. toCheck := filtered(canGo, valves, []string{})
  181. result := calculate(toCheck, valves, []string{}, 0, 0)
  182. return result
  183. }
  184. func main() {
  185. if len(os.Args) < 2 {
  186. log.Fatal("You need to specify a file!")
  187. }
  188. filePath := os.Args[1]
  189. file, err := os.Open(filePath)
  190. if err != nil {
  191. log.Fatalf("Failed to open %s!\n", filePath)
  192. }
  193. vertices, valves := readInput(file)
  194. graph := buildGraph(valves)
  195. generatePaths(vertices, graph, valves)
  196. fmt.Println("Part1:", part1(vertices[0], valves))
  197. }