code.go 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252
  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 setStart(from vertex, vertices []vertex) {
  86. for i := range vertices {
  87. if vertices[i].name == from.name {
  88. vertices[i].visited = true
  89. vertices[i].cost = 0
  90. }
  91. }
  92. }
  93. func getNext(vertices []vertex) *vertex {
  94. min := maxValue
  95. var current *vertex
  96. for i := range vertices {
  97. if vertices[i].visited {
  98. continue
  99. }
  100. if vertices[i].cost <= min {
  101. min = vertices[i].cost
  102. current = &vertices[i]
  103. }
  104. }
  105. return current
  106. }
  107. func traverse(from vertex, vertices []vertex, graph []path) []vertex {
  108. newVertices := make([]vertex, len(vertices))
  109. copy(newVertices, vertices)
  110. current := &from
  111. setStart(*current, newVertices)
  112. for {
  113. for j := range graph {
  114. if graph[j].from != current.name {
  115. continue
  116. }
  117. var tentativeCost int
  118. if current.cost == maxValue {
  119. tentativeCost = maxValue
  120. } else {
  121. tentativeCost = current.cost + 1
  122. }
  123. if tentativeCost < getCost(graph[j].to, newVertices) {
  124. setCost(graph[j].to, tentativeCost, newVertices)
  125. }
  126. }
  127. current.visited = true
  128. current = getNext(newVertices)
  129. if current == nil {
  130. break
  131. }
  132. }
  133. return newVertices
  134. }
  135. func generatePaths(vertices []vertex, graph []path, valves map[string]valve) {
  136. for key, value := range valves {
  137. value.paths = traverse(vertex{value.name, 0, false}, vertices, graph)
  138. valves[key] = value
  139. }
  140. }
  141. func contains(visited []string, name string) bool {
  142. for i := range visited {
  143. if visited[i] == name {
  144. return true
  145. }
  146. }
  147. return false
  148. }
  149. func filtered(vertices []vertex, valves map[string]valve, visited []string) []vertex {
  150. var result []vertex
  151. for i := range vertices {
  152. if contains(visited, vertices[i].name) {
  153. continue
  154. }
  155. val, _ := valves[vertices[i].name]
  156. if val.rate > 0 {
  157. result = append(result, vertices[i])
  158. }
  159. }
  160. return result
  161. }
  162. func calculate(moveTo []vertex, valves map[string]valve, visited []string, count int, rate int) int {
  163. if count >= 30 || len(moveTo) == 0 {
  164. return rate
  165. }
  166. max := 0
  167. for i := range moveTo {
  168. currentCount := count + moveTo[i].cost + 1
  169. if currentCount > 30 {
  170. continue
  171. }
  172. val, _ := valves[moveTo[i].name]
  173. val.open = true
  174. valves[moveTo[i].name] = val
  175. newVisited := make([]string, len(visited))
  176. copy(newVisited, visited)
  177. newVisited = append(newVisited, moveTo[i].name)
  178. canGo := valves[moveTo[i].name].paths
  179. toCheck := filtered(canGo, valves, newVisited)
  180. result := calculate(toCheck, valves, newVisited, currentCount, rate+(30-currentCount)*val.rate)
  181. if result > max {
  182. max = result
  183. }
  184. }
  185. return max
  186. }
  187. func part1(from vertex, valves map[string]valve) int {
  188. canGo := valves[from.name].paths
  189. toCheck := filtered(canGo, valves, []string{})
  190. result := calculate(toCheck, valves, []string{}, 0, 0)
  191. return result
  192. }
  193. func main() {
  194. if len(os.Args) < 2 {
  195. log.Fatal("You need to specify a file!")
  196. }
  197. filePath := os.Args[1]
  198. file, err := os.Open(filePath)
  199. if err != nil {
  200. log.Fatalf("Failed to open %s!\n", filePath)
  201. }
  202. vertices, valves := readInput(file)
  203. graph := buildGraph(valves)
  204. generatePaths(vertices, graph, valves)
  205. fmt.Println("Part1:", part1(vertices[0], valves))
  206. }