solve_2.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. package main
  2. import (
  3. "bufio"
  4. "fmt"
  5. "os"
  6. )
  7. type coord struct {
  8. x,y int
  9. }
  10. func main() {
  11. fmt.Println("Advent of Code - Day 7 - Part 2")
  12. f,_ := os.Open("7/input")
  13. defer f.Close()
  14. scanner := bufio.NewScanner(f)
  15. y := 0
  16. scanner.Scan()
  17. y_limit := len(scanner.Text())
  18. for i := range(scanner.Text()){
  19. if scanner.Text()[i] == 'S'{
  20. y = i
  21. }
  22. }
  23. initial_position := coord{0,y}
  24. x:=1
  25. var splitters []coord
  26. for scanner.Scan(){
  27. line := scanner.Text()
  28. for i:= range line{
  29. if line[i] == '^'{
  30. splitters = append(splitters, coord{x,i})
  31. }
  32. }
  33. x++
  34. }
  35. limit := coord{x,y_limit}
  36. res := 0
  37. store_split := make(map[coord]int)
  38. res = count_timelines(initial_position, splitters, limit, &store_split)
  39. fmt.Println(res)
  40. }
  41. func count_timelines(pos coord, splitters []coord, limit coord, store_split* map[coord]int) int {
  42. ss, ok := (*store_split)[pos]
  43. if ok {
  44. return ss
  45. }
  46. if pos.x >= limit.x || pos.y >= limit.y || pos.y < 0 {
  47. return 1
  48. }
  49. for _,s := range splitters {
  50. if pos.x == s.x && pos.y == s.y {
  51. n_pos1:=coord{pos.x, pos.y-1}
  52. n_pos2:=coord{pos.x, pos.y+1}
  53. (*store_split)[n_pos1] = count_timelines(coord{pos.x,pos.y-1},splitters, limit, store_split)
  54. (*store_split)[n_pos2] = count_timelines(coord{pos.x,pos.y+1},splitters, limit, store_split)
  55. return (*store_split)[n_pos1] + (*store_split)[n_pos2]
  56. }
  57. }
  58. n_pos := coord{pos.x+1,pos.y}
  59. (*store_split)[n_pos] = count_timelines(coord{pos.x+1,pos.y},splitters, limit, store_split)
  60. return (*store_split)[n_pos]
  61. }