Skip to content

Instantly share code, notes, and snippets.

@DeepFriedTwinkie
Last active December 15, 2016 18:34
Show Gist options
  • Save DeepFriedTwinkie/b47534bad29f86c79176bfd02b37f444 to your computer and use it in GitHub Desktop.
Save DeepFriedTwinkie/b47534bad29f86c79176bfd02b37f444 to your computer and use it in GitHub Desktop.
AdventOfCode.com 2016/Day 3, Part 2 Solution
import Foundation
//: ## Helpers
func string(fromFile name:String, fileExtension:String) -> String? {
if let filePath = Bundle.main.path(forResource:name, ofType:fileExtension) {
if let inputData = FileManager.default.contents(atPath: filePath) {
return String(data: inputData, encoding: .utf8)
}
}
return nil
}
//: ## Solution Objects
struct Triangle {
let vertices: [Int]
init?(vertices:[Int]) {
guard vertices.count == 3 else { return nil }
guard vertices[0] + vertices[1] > vertices[2],
vertices[0] + vertices[2] > vertices[1],
vertices[2] + vertices[1] > vertices[0] else {
return nil
}
self.vertices = vertices
}
}
//: ## Input Processing
let day = "Day3"
let testInput = " 330 143 338"
func prepareInput() -> [[Int]] {
if let inputString = string(fromFile: day, fileExtension: "txt") {
let triangleStrings = inputString.components(separatedBy: "\n") // Split each line into a string that might represent an array of vertices
return triangleStrings.map { (vertexString) -> [Int] in // For each line in the input file...
return vertexString.components(separatedBy: CharacterSet(charactersIn: " ")) // Split the string into strings by spaces...
.flatMap({ return Int($0) }) // Convert those strings to Ints...
}
}
return [[Int]]()
}
let triangles = prepareInput()
//: ## Solution Execution
var actualTriangles = [Triangle]()
var index = triangles.startIndex
while index < triangles.endIndex {
let endIndex = triangles.index(index, offsetBy: 2)
guard endIndex < triangles.endIndex else { break }
let triple = triangles[index...endIndex]
for column in 0...2 {
if let triangle = Triangle(vertices: triple.map({ return $0[column] })) {
actualTriangles.append(triangle)
}
}
index = triangles.index(index, offsetBy: 3)
}
print("\(actualTriangles.count)")
@DeepFriedTwinkie
Copy link
Author

The swift array indexing could use some work. This is hacky. Need to look at Collection and Sequence protocols for more inspiration!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment