Files
aoc24/day08/d08p1.swift
2024-12-13 15:04:22 -08:00

43 lines
1.3 KiB
Swift

import Foundation
struct Point : Hashable {
let x: Int
let y: Int
}
func readInput(_ filePath: String) throws -> (Int, Int, [Character: [Point]]) {
let content = try String(contentsOfFile: filePath, encoding: .ascii)
let lines = content.split(separator: "\n").map(Array.init)
let antennas = lines.enumerated().flatMap { i, line in
line.enumerated().compactMap { j, cell in
cell == "." ? nil : (cell, i, j)
}
}
var map: [Character: [Point]] = [:]
for (type, i, j) in antennas {
let current = map[type, default: []]
map[type] = current + [Point(x: i, y: j)]
}
return (lines.count, lines[0].count, map)
}
func nodes(_ antennas: [Point]) -> Set<Point> {
var nodes: Set<Point> = []
for i in 0..<antennas.count {
for j in i+1..<antennas.count {
let (a, b) = (antennas[i], antennas[j])
nodes.insert(Point(x: 2*a.x - b.x, y: 2*a.y - b.y))
nodes.insert(Point(x: 2*b.x - a.x, y: 2*b.y - a.y))
}
}
return nodes
}
let (height, width, antennas) = try readInput(CommandLine.arguments[1])
let answer = antennas
.map { c, points in nodes(points) }
.reduce(Set([]), { acc, x in acc.union(x) })
.filter { p in p.x >= 0 && p.y >= 0 && p.x < height && p.y < width }
.count
print(answer)