aoc2021/Sources/02/02.swift
2021-12-08 21:22:44 +01:00

91 lines
2.0 KiB
Swift

//
// File.swift
//
//
// Created by Max Nuding on 02.12.21.
//
import Foundation
import Runner
enum Direction: String {
case forward
case down
case up
init?(rawValue: String) {
switch rawValue {
case "forward":
self = .forward
case "down":
self = .down
case "up":
self = .up
default:
return nil
}
}
}
struct MoveCommand {
let direction: Direction
let amount: Int
init?(line: String) {
guard !line.isEmpty else {
return nil
}
let parts = line.components(separatedBy: .whitespaces)
direction = Direction(rawValue: parts[0])!
amount = Int(parts[1])!
}
}
struct Day02: Runnable {
let inputPath: String
func run() {
let input = try! String(contentsOfFile: inputPath)
let commands = input
.components(separatedBy: .newlines)
.compactMap { MoveCommand(line: $0) }
runA(commands: commands)
runB(commands: commands)
}
func runA(commands: [MoveCommand]) {
var horizontalPos = 0
var depth = 0
for command in commands {
switch command.direction {
case .forward:
horizontalPos += command.amount
case .up:
depth -= command.amount
case .down:
depth += command.amount
}
}
print(horizontalPos * depth)
}
func runB(commands: [MoveCommand]) {
var horizontalPos = 0
var depth = 0
var aim = 0
for command in commands {
switch command.direction {
case .forward:
horizontalPos += command.amount
depth += aim * command.amount
case .up:
aim -= command.amount
case .down:
aim += command.amount
}
}
print(horizontalPos * depth)
}
}