day4.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115
  1. package main
  2. import (
  3. "bufio"
  4. "flag"
  5. "fmt"
  6. "os"
  7. "slices"
  8. )
  9. func main() {
  10. args := flag.Bool("example", false, "example or input")
  11. flag.Parse()
  12. filename := "input.txt"
  13. if *args {
  14. filename = "example.txt"
  15. }
  16. file, err := os.Open(filename)
  17. if err != nil {
  18. fmt.Println(err)
  19. return
  20. }
  21. defer file.Close()
  22. var grid []string
  23. reader := bufio.NewReader(file)
  24. for {
  25. line, _, _ := reader.ReadLine()
  26. if len(line) == 0 {
  27. break
  28. }
  29. grid = append(grid, string(line))
  30. }
  31. rows := len(grid)
  32. cols := len(grid[0])
  33. xmas := "XMAS"
  34. mas := "MAS"
  35. directions := [][2]int{
  36. {0, 1}, // →
  37. {0, -1}, // ←
  38. {-1, 0}, // ↓
  39. {1, 0}, // ↑
  40. {1, 1}, // ↘
  41. {-1, -1}, // ↖
  42. {-1, 1}, // ↗
  43. {1, -1}, // ↙
  44. }
  45. uniqueWords := make(map[[3]int]bool) // [row, col, directionIndex]
  46. isXMAS := func(startRow, startCol, dirX, dirY int) bool {
  47. for i := 0; i < len(xmas); i++ {
  48. newRow := startRow + i*dirX
  49. newCol := startCol + i*dirY
  50. if newRow < 0 || newRow >= rows || newCol < 0 || newCol >= cols || grid[newRow][newCol] != xmas[i] {
  51. return false
  52. }
  53. }
  54. return true
  55. }
  56. isMAS := func(diagonal []byte) bool {
  57. line := string(diagonal)
  58. slices.Reverse(diagonal)
  59. return line == mas || string(diagonal) == mas
  60. }
  61. totalCount := 0
  62. totalXmas := 0
  63. // part1
  64. for row := 0; row < rows; row++ {
  65. for col := 0; col < cols; col++ {
  66. if grid[row][col] == 'X' {
  67. for dirIndex, dir := range directions {
  68. dirX, dirY := dir[0], dir[1]
  69. if isXMAS(row, col, dirX, dirY) {
  70. key := [3]int{row, col, dirIndex}
  71. if !uniqueWords[key] {
  72. uniqueWords[key] = true
  73. totalCount++
  74. }
  75. }
  76. }
  77. }
  78. }
  79. }
  80. //part2
  81. for row := 1; row < rows-1; row++ {
  82. for col := 1; col < cols-1; col++ {
  83. if grid[row][col] == 'A' {
  84. // ↘
  85. diagonal1 := []byte{
  86. grid[row-1][col-1],
  87. grid[row][col],
  88. grid[row+1][col+1],
  89. }
  90. // ↖
  91. diagonal2 := []byte{
  92. grid[row+1][col-1],
  93. grid[row][col],
  94. grid[row-1][col+1],
  95. }
  96. if isMAS(diagonal1) && isMAS(diagonal2) {
  97. totalXmas++
  98. }
  99. }
  100. }
  101. }
  102. fmt.Println("Total count of XMAS:", totalCount)
  103. fmt.Println("Total count of X-MAS:", totalXmas)
  104. }