package day_04 import "strings" // task:https://adventofcode.com/2024/day/2 // short summary - count all instances of XMAS in the 2d array func SolveBasic(input string) int { grid := toGrid(input) found := 0 for y := 0; y < len(grid); y++ { for x := 0; x < len(grid[y]); x++ { if grid[y][x] == 'X' { found += checkForXMAS(grid, x, y) } } } return found } // task:https://adventofcode.com/2024/day/2#part2 // short summary - func SolveComplex(input string) int { grid := toGrid(input) found := 0 for y := 1; y < len(grid)-1; y++ { for x := 1; x < len(grid[y])-1; x++ { if grid[y][x] == 'A' { if checkForX_MAS(grid, x, y) { found++ } } } } return found } // helper methods func toGrid(input string) [][]rune { substrings := strings.Split(input, "\n") var grid [][]rune for _, line := range substrings { grid = append(grid, []rune(line)) } return grid } func checkForXMAS(grid [][]rune, x int, y int) int { found := 0 // going clockwise from top left if x >= 3 && y >= 3 { if checkLineForXMAS(grid, x, y, -1, -1) { found++ } } if y >= 3 { if checkLineForXMAS(grid, x, y, 0, -1) { found++ } } if y >= 3 && x < len(grid[y])-3 { if checkLineForXMAS(grid, x, y, 1, -1) { found++ } } if x < len(grid[y])-3 { if checkLineForXMAS(grid, x, y, 1, 0) { found++ } } if y < len(grid)-3 && x < len(grid[y])-3 { if checkLineForXMAS(grid, x, y, 1, 1) { found++ } } if y < len(grid)-3 { if checkLineForXMAS(grid, x, y, 0, 1) { found++ } } if x >= 3 && y < len(grid)-3 { if checkLineForXMAS(grid, x, y, -1, 1) { found++ } } if x >= 3 { if checkLineForXMAS(grid, x, y, -1, 0) { found++ } } return found } func checkForX_MAS(grid [][]rune, x int, y int) bool { // M.M // .A. // S.S if grid[y-1][x-1] == 'M' && grid[y-1][x+1] == 'M' && grid[y+1][x-1] == 'S' && grid[y+1][x+1] == 'S' { return true } // S.M // .A. // S.M if grid[y-1][x-1] == 'S' && grid[y-1][x+1] == 'M' && grid[y+1][x-1] == 'S' && grid[y+1][x+1] == 'M' { return true } // M.S // .A. // M.S if grid[y-1][x-1] == 'M' && grid[y-1][x+1] == 'S' && grid[y+1][x-1] == 'M' && grid[y+1][x+1] == 'S' { return true } // S.S // .A. // M.M if grid[y-1][x-1] == 'S' && grid[y-1][x+1] == 'S' && grid[y+1][x-1] == 'M' && grid[y+1][x+1] == 'M' { return true } return false } func checkLineForXMAS(grid [][]rune, x int, y int, xStep int, yStep int) bool { return grid[y+yStep][x+xStep] == 'M' && grid[y+2*yStep][x+2*xStep] == 'A' && grid[y+3*yStep][x+3*xStep] == 'S' }