Attempting the Advent of Code using Swift?
Don't bother finding the input files ; or hard-coding the puzzle input, use this template intead to start quickly!
input.txt
file, or override static func rawInput() async throws -> String
static func rawInput() async throws -> String {
"iwrupvqb"
}
struct Day01: Puzzle {
typealias Input = String
typealias OutputPartOne = Int
typealias OutputPartTwo = Int
}
static var partOneExpectations: [any Expectation<Input, OutputPartOne>] {
[
assert(expectation: 1, from: ")"),
assert(expectation: 5, from: "()())"),
...
]
}
static func solvePartOne(_ input: Input) async throws
until tests are passingstatic var partTwoExpectations
and static func solvePartTwo(_ input: Input) async throws
Often, you'll require your own types. This will require to make them "Parsable"
Simply implement the Parsable protocol, and then use your type as an Input:
struct Box: Parsable { ... }
struct Day02: Puzzle {
typealias Input = Box
}
Your parsable type can also be implicitly passed in an array. In that case, the separation of the input will use static var componentsSeparator: CharacterSet
to separate the Input before calling static parse(raw: String)
:
struct Box: Parsable { ... }
struct Day02: Puzzle {
typealias Input = [Box]
}
To test your parsing code, you can also use assertion to use "raw" input instead of parsed input:
static var partOneExpectations: [any Expectation<Input, OutputPartOne>] {
[
// Either provide the fully parsed input (your type))
assert(expectation: 58, from: [.init(small: 2, medium: 3, large: 4)],
// Or a raw string that should be parsed (this will allow to test your parsing code as well)
assert(expectation: 43, fromRaw: "1x1x10"),
...
]
}
throw InputError.unexpectedInput
or throw InputError.couldNotCast(target: Double.self)
throw ExecutionError.unsolvable
The first four days of 2015 have been solved, and hare in the Examples folder. They give some input on what your solution could look like when using this template.
Help the project improve itself with your suggestions, issues and pull requests!
link |
Stars: 11 |
Last commit: 1 year ago |
Swiftpack is being maintained by Petr Pavlik | @ptrpavlik | @swiftpackco | API | Analytics