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