code.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126
  1. package main
  2. import (
  3. "fmt"
  4. "io/ioutil"
  5. "log"
  6. "os"
  7. "strings"
  8. )
  9. func readInput(file string) [][]string {
  10. content, err := ioutil.ReadFile(file)
  11. if err != nil {
  12. log.Fatal(err)
  13. }
  14. lines := strings.Split(string(content), "\n")
  15. var input [][]string
  16. for _, line := range lines {
  17. if line == "" {
  18. continue
  19. }
  20. row := strings.Split(line, "")
  21. input = append(input, row)
  22. }
  23. return input
  24. }
  25. func moveEast(input [][]string) (bool, [][]string) {
  26. changed := false
  27. newBoard := make([][]string, len(input))
  28. for i := 0; i < len(input); i++ {
  29. newBoard[i] = make([]string, len(input[i]))
  30. }
  31. for i := 0; i < len(input); i++ {
  32. for j := 0; j < len(input[i]); j++ {
  33. if input[i][j] == ">" {
  34. if j+1 < len(input[i]) {
  35. if input[i][j+1] == "." {
  36. newBoard[i][j] = "."
  37. newBoard[i][j+1] = ">"
  38. changed = true
  39. continue
  40. }
  41. } else {
  42. if input[i][0] == "." {
  43. newBoard[i][j] = "."
  44. newBoard[i][0] = ">"
  45. changed = true
  46. }
  47. }
  48. }
  49. if newBoard[i][j] == "" {
  50. newBoard[i][j] = input[i][j]
  51. }
  52. }
  53. }
  54. return changed, newBoard
  55. }
  56. func moveSouth(input [][]string) (bool, [][]string) {
  57. changed := false
  58. newBoard := make([][]string, len(input))
  59. for i := 0; i < len(input); i++ {
  60. newBoard[i] = make([]string, len(input[i]))
  61. }
  62. for i := 0; i < len(input); i++ {
  63. for j := 0; j < len(input[i]); j++ {
  64. if input[i][j] == "v" {
  65. if i+1 < len(input) {
  66. if input[i+1][j] == "." {
  67. newBoard[i][j] = "."
  68. newBoard[i+1][j] = "v"
  69. changed = true
  70. continue
  71. }
  72. } else {
  73. if input[0][j] == "." {
  74. newBoard[i][j] = "."
  75. newBoard[0][j] = "v"
  76. changed = true
  77. continue
  78. }
  79. }
  80. }
  81. if newBoard[i][j] == "" {
  82. newBoard[i][j] = input[i][j]
  83. }
  84. }
  85. }
  86. return changed, newBoard
  87. }
  88. func part1(input [][]string) int {
  89. count := 1
  90. var changedEast, changedSouth bool
  91. for {
  92. changedEast, input = moveEast(input)
  93. changedSouth, input = moveSouth(input)
  94. if !changedEast && !changedSouth {
  95. break
  96. }
  97. count++
  98. }
  99. return count
  100. }
  101. func main() {
  102. if len(os.Args) < 2 {
  103. log.Fatal("Please provide a file name as argument")
  104. }
  105. input := readInput(os.Args[1])
  106. fmt.Println("Part1:", part1(input))
  107. }