code.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134
  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 {
  26. changed := false
  27. for i := 0; i < len(input); i++ {
  28. for j := 0; j < len(input[i]); j++ {
  29. if input[i][j] == "." || input[i][j] == "v" {
  30. continue
  31. }
  32. if input[i][j] == ">" {
  33. if j+1 < len(input[i]) {
  34. if input[i][j+1] == "." {
  35. input[i][j] = "."
  36. input[i][j+1] = ">"
  37. changed = true
  38. j++
  39. continue
  40. }
  41. } else {
  42. if input[i][0] == "." {
  43. input[i][j] = "."
  44. input[i][0] = ">"
  45. changed = true
  46. }
  47. }
  48. }
  49. }
  50. }
  51. return changed
  52. }
  53. type point struct {
  54. x, y int
  55. }
  56. func moveSouth(input [][]string) bool {
  57. changed := false
  58. toSkip := make(map[point]bool)
  59. for i := 0; i < len(input); i++ {
  60. for j := 0; j < len(input[i]); j++ {
  61. if toSkip[point{i, j}] {
  62. continue
  63. }
  64. if input[i][j] == "." || input[i][j] == ">" {
  65. continue
  66. }
  67. if input[i][j] == "v" {
  68. if i+1 < len(input) {
  69. if input[i+1][j] == "." {
  70. input[i][j] = "."
  71. input[i+1][j] = "v"
  72. toSkip[point{i + 1, j}] = true
  73. changed = true
  74. continue
  75. }
  76. } else {
  77. if input[0][j] == "." {
  78. input[i][j] = "."
  79. input[0][j] = "v"
  80. changed = true
  81. }
  82. }
  83. }
  84. }
  85. }
  86. return changed
  87. }
  88. func print(input [][]string) {
  89. for _, row := range input {
  90. fmt.Println(row)
  91. }
  92. fmt.Println()
  93. }
  94. func part1(input [][]string) int {
  95. count := 0
  96. for i := 0; i < 10; i++ {
  97. fmt.Println(count)
  98. print(input)
  99. changedEast := moveEast(input)
  100. changedSouth := moveSouth(input)
  101. if !changedEast && !changedSouth {
  102. break
  103. }
  104. count++
  105. }
  106. return count
  107. }
  108. func main() {
  109. if len(os.Args) < 2 {
  110. log.Fatal("Please provide a file name as argument")
  111. }
  112. input := readInput(os.Args[1])
  113. fmt.Println("Part1:", part1(input))
  114. }