aoc2021/Sources/13/13.swift
2021-12-13 07:45:12 +01:00

114 lines
2.6 KiB
Swift

//
// File.swift
//
//
// Created by Max Nuding on 12.12.21.
//
import Foundation
import Runner
struct Coord: Hashable {
var x: Int
var y: Int
init(x: Int, y: Int) {
self.x = x
self.y = y
}
init(line: String) {
let parts = line.split(separator: ",").map { Int($0)! }
x = parts.first!
y = parts.last!
}
func foldingUp(by y: Int) -> Coord {
guard self.y > y else {
return self
}
return Coord(x: x, y: y - (self.y - y))
}
func foldingLeft(by x: Int) -> Coord {
guard self.x > x else {
return self
}
return Coord(x: x - (self.x - x), y: y)
}
func folding(by instruction: FoldingInstruction) -> Coord {
switch instruction {
case .up(let y):
return foldingUp(by: y)
case .left(let x):
return foldingLeft(by: x)
}
}
}
enum FoldingInstruction {
case up(y: Int)
case left(x: Int)
init?(line: String) {
let i = line.split(separator: " ").last!.split(separator: "=")
let coord = Int(i.last!)!
switch i.first {
case "x":
self = .left(x: coord)
case "y":
self = .up(y: coord)
default:
return nil
}
}
}
class Day13: Runnable {
let inputPath: String
required init(inputPath: String) {
self.inputPath = inputPath
}
public func run() {
let input = try! String(contentsOfFile: inputPath)
let parts = input
.trimmingCharacters(in: .newlines)
.components(separatedBy: "\n\n")
var dots = parts.first!
.components(separatedBy: .newlines)
.map(Coord.init)
let instructions = parts.last!
.components(separatedBy: .newlines)
.map { FoldingInstruction(line: $0)! }
var isFirst = true
for instruction in instructions {
dots = dots.map { $0.folding(by: instruction) }
if isFirst {
print(Set(dots).count)
isFirst = false
}
}
printDots(dots: dots)
}
func printDots(dots:[Coord]) {
let maxX = dots.map {$0.x}.max()!
let maxY = dots.map {$0.y}.max()!
let uniqueDots = Set(dots)
var s = ""
for y in 0...maxY {
for x in 0...maxX {
s += uniqueDots.contains(Coord(x: x, y: y)) ? "#" : " "
}
s += "\n"
}
print(s)
}
}