aoc2021/Sources/13/13.swift

114 lines
2.6 KiB
Swift
Raw Permalink Normal View History

2021-12-13 06:34:17 +00:00
//
// 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)! }
2021-12-13 06:44:50 +00:00
var isFirst = true
2021-12-13 06:34:17 +00:00
for instruction in instructions {
dots = dots.map { $0.folding(by: instruction) }
2021-12-13 06:44:50 +00:00
if isFirst {
print(Set(dots).count)
isFirst = false
}
2021-12-13 06:34:17 +00:00
}
2021-12-13 06:44:50 +00:00
printDots(dots: dots)
2021-12-13 06:34:17 +00:00
}
func printDots(dots:[Coord]) {
let maxX = dots.map {$0.x}.max()!
let maxY = dots.map {$0.y}.max()!
2021-12-13 06:44:50 +00:00
let uniqueDots = Set(dots)
var s = ""
for y in 0...maxY {
for x in 0...maxX {
2021-12-13 06:45:12 +00:00
s += uniqueDots.contains(Coord(x: x, y: y)) ? "#" : " "
2021-12-13 06:34:17 +00:00
}
2021-12-13 06:44:50 +00:00
s += "\n"
2021-12-13 06:34:17 +00:00
}
2021-12-13 06:44:50 +00:00
print(s)
2021-12-13 06:34:17 +00:00
}
}