|
| 1 | +import Algorithms |
| 2 | + |
| 3 | +func searchInNeighbors(pos: Coord, _ grid: Grid) -> [Coord] { |
| 4 | + pos.fullNeighbors.included(in: grid).filter { n in |
| 5 | + grid[n] == "M" |
| 6 | + } |
| 7 | +} |
| 8 | + |
| 9 | +func isMAS(pos: Coord, _ grid: Grid) -> Bool { |
| 10 | + let candidates = pos.cornerNeighbors |
| 11 | + if (candidates.allSatisfy { $0.isInside(grid: grid) }) { |
| 12 | + let l = candidates.map { grid[$0] } |
| 13 | + let letterSet = Set(l) |
| 14 | + // same letter can not be on opposite side |
| 15 | + return l[0] != l[2] && l[1] != l[3] && letterSet.count == 2 && letterSet == ["M", "S"] |
| 16 | + } |
| 17 | + return false |
| 18 | +} |
| 19 | + |
| 20 | +func isWhole(pos: Coord, inDir: Coord, grid: Grid) -> Bool { |
| 21 | + let aPos = pos + inDir |
| 22 | + let sPos = aPos + inDir |
| 23 | + if aPos.isInside(grid: grid) && sPos.isInside(grid: grid) { |
| 24 | + return grid[aPos] == "A" && grid[sPos] == "S" |
| 25 | + } |
| 26 | + return false |
| 27 | +} |
| 28 | + |
| 29 | +struct Day04: AdventDay { |
| 30 | + var data: String |
| 31 | + var grid: Grid { |
| 32 | + Grid(from: data) |
| 33 | + } |
| 34 | + |
| 35 | + func countAllWhere(letter search: Character, predicate: (Coord, Grid) -> Bool) -> Int { |
| 36 | + grid.raw.enumerated().map { (y, line) in |
| 37 | + line.enumerated().map { (x, letter) in |
| 38 | + if letter == search { |
| 39 | + return predicate(Coord(x: x, y: y), grid) |
| 40 | + } |
| 41 | + return false |
| 42 | + } |
| 43 | + }.flatMap { $0 }.count { $0 == true } |
| 44 | + } |
| 45 | + |
| 46 | + func part1() -> Int { |
| 47 | + var count = 0 |
| 48 | + // get all positions of "X" |
| 49 | + for (y, line) in grid.raw.enumerated() { |
| 50 | + for (x, letter) in line.enumerated() { |
| 51 | + if letter == "X" { |
| 52 | + let currentPos = Coord(x: x, y: y) |
| 53 | + let results = searchInNeighbors(pos: currentPos, grid) |
| 54 | + if results.count > 0 { |
| 55 | + for candidate in results { |
| 56 | + let inDir = candidate - currentPos |
| 57 | + if isWhole(pos: candidate, inDir: inDir, grid: grid) { |
| 58 | + count += 1 |
| 59 | + } |
| 60 | + } |
| 61 | + } |
| 62 | + } |
| 63 | + } |
| 64 | + } |
| 65 | + return count |
| 66 | + } |
| 67 | + |
| 68 | + func part2() -> Int { |
| 69 | + countAllWhere(letter: "A", predicate: isMAS) |
| 70 | + } |
| 71 | +} |
0 commit comments