This commit is contained in:
Max Nuding 2021-12-02 07:04:34 +01:00
parent e233a21d36
commit bceb0b5405
Signed by: phlaym
GPG Key ID: A06651BAB6777237
3 changed files with 1099 additions and 0 deletions

89
Sources/aoc2021/02.swift Normal file
View File

@ -0,0 +1,89 @@
//
// File.swift
//
//
// Created by Max Nuding on 02.12.21.
//
import Foundation
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 {
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)
}
}

File diff suppressed because it is too large Load Diff

View File

@ -1,5 +1,6 @@
import Foundation
/*
print("Starting day 01")
let input01 = Bundle.module.path(forResource: "01", ofType: ".txt")!
let start = CFAbsoluteTimeGetCurrent()
@ -7,3 +8,12 @@ Day01(inputPath: input01).run()
let end = CFAbsoluteTimeGetCurrent()
let execTimeMs = round((end - start) * 1000.0 * 100.0) / 100.0
print("Finished in \(execTimeMs)ms")
*/
print("Starting day 02")
let input02 = Bundle.module.path(forResource: "02", ofType: ".txt")!
let start = CFAbsoluteTimeGetCurrent()
Day02(inputPath: input02).run()
let end = CFAbsoluteTimeGetCurrent()
let execTimeMs = round((end - start) * 1000.0 * 100.0) / 100.0
print("Finished in \(execTimeMs)ms")