aoc2021/Sources/02/02.swift

91 lines
2.0 KiB
Swift
Raw Permalink Normal View History

2021-12-02 06:04:34 +00:00
//
// File.swift
//
//
// Created by Max Nuding on 02.12.21.
//
import Foundation
2021-12-08 20:22:44 +00:00
import Runner
2021-12-02 06:04:34 +00:00
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])!
}
}
2021-12-05 10:43:02 +00:00
struct Day02: Runnable {
2021-12-02 06:04:34 +00:00
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)
}
}