import Foundation func readInput(_ filePath: String) throws -> [[Character]] { let content = try String(contentsOfFile: filePath, encoding: .ascii) return content.split(separator: "\n").map(Array.init) } let XMAS: (Character, Character, Character, Character) = ("X", "M", "A", "S") func dE(_ map: [[Character]], _ i: Int, _ j: Int) -> Bool { return j < map[i].count - 3 && (map[i][j], map[i][j+1], map[i][j+2], map[i][j+3]) == XMAS } func dW(_ map: [[Character]], _ i: Int, _ j: Int) -> Bool { return j >= 3 && (map[i][j], map[i][j-1], map[i][j-2], map[i][j-3]) == XMAS } func dS(_ map: [[Character]], _ i: Int, _ j: Int) -> Bool { return i < map.count - 3 && (map[i][j], map[i+1][j], map[i+2][j], map[i+3][j]) == XMAS } func dN(_ map: [[Character]], _ i: Int, _ j: Int) -> Bool { return i >= 3 && (map[i][j], map[i-1][j], map[i-2][j], map[i-3][j]) == XMAS } func dNW(_ map: [[Character]], _ i: Int, _ j: Int) -> Bool { return i >= 3 && j >= 3 && (map[i][j], map[i-1][j-1], map[i-2][j-2], map[i-3][j-3]) == XMAS } func dSE(_ map: [[Character]], _ i: Int, _ j: Int) -> Bool { return i < map.count - 3 && j < map[i].count - 3 && (map[i][j], map[i+1][j+1], map[i+2][j+2], map[i+3][j+3]) == XMAS } func dNE(_ map: [[Character]], _ i: Int, _ j: Int) -> Bool { return i >= 3 && j < map[i].count - 3 && (map[i][j], map[i-1][j+1], map[i-2][j+2], map[i-3][j+3]) == XMAS } func dSW(_ map: [[Character]], _ i: Int, _ j: Int) -> Bool { return i < map.count - 3 && j >= 3 && (map[i][j], map[i+1][j-1], map[i+2][j-2], map[i+3][j-3]) == XMAS } func xmasCount(_ map: [[Character]], _ i: Int, _ j: Int) -> Int { let funcs = [dE, dW, dS, dN, dNW, dSE, dNE, dSW] return funcs.reduce(0, { sum, f in f(map, i, j) ? sum+1 : sum }) } let input = try readInput(CommandLine.arguments[1]) let answer = (0..