Skip to content

Instantly share code, notes, and snippets.

@DeepFriedTwinkie
Created December 18, 2016 18:30
Show Gist options
  • Save DeepFriedTwinkie/ea4644e3ee555e86a8e5aea86fd1c5e1 to your computer and use it in GitHub Desktop.
Save DeepFriedTwinkie/ea4644e3ee555e86a8e5aea86fd1c5e1 to your computer and use it in GitHub Desktop.
AdventOfCode.com 2016/Day 6 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 and Functions
enum OrderBy {
case ascending
case descending
}
func commonCharsString(counts:[[Character:Int]], orderedBy:OrderBy) -> String {
let reverseSort = orderedBy == .descending
return String(counts.flatMap {
return $0.sorted(by: {
if reverseSort {
if $0.value == $1.value { return $0.key > $1.key }
return $0.value < $1.value
} else {
if $0.value == $1.value { return $0.key < $1.key }
return $0.value > $1.value
}
}).first?.key
})
}
//: ## Input Processing
let day = "Day6"
let testInput = "eedadn\ndrvtee\neandsr\nraavrd\natevrs\ntsrnev\nsdttsa\nrasrtv\nnssdts\nntnada\nsvetve\ntesnvt\nvntsnd\nvrdear\ndvrsen\nenarar"
func prepareInput() -> [String] {
if let inputString = string(fromFile: day, fileExtension: "txt") {
return inputString.components(separatedBy: "\n")
}
return [String]()
}
let messages = prepareInput()
//let messages = testInput.components(separatedBy: "\n")
//: ## Solution Execution
//: ### Part 1
var counts = Array(repeatElement([Character:Int](), count: 8))
// Sum Characters
for message in messages {
for (position,char) in message.characters.enumerated() {
var count = counts[position]
counts[position][char] = counts[position][char]?.advanced(by: 1) ?? 1
}
}
let mostCommonMessage = commonCharsString(counts: counts, orderedBy: .descending)
print("Part 1 Answer: \(mostCommonMessage)\n")
//: ### Part 2
let leastCommonMessage = commonCharsString(counts: counts, orderedBy: .ascending)
print("Part 2 Answer: \(leastCommonMessage)")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment