Skip to content

Instantly share code, notes, and snippets.

@proxpero
Created December 2, 2018 06:59
Show Gist options
  • Save proxpero/918effff0ecddaa7ffc1a03d4a466ca9 to your computer and use it in GitHub Desktop.
Save proxpero/918effff0ecddaa7ffc1a03d4a466ca9 to your computer and use it in GitHub Desktop.
Advent of Code 2018, day 2
// Part 1
extension String {
var characterCounts: [Character: Int] {
return self.reduce(into: [Character: Int]()) { $0[$1, default: 0] += 1 }
}
}
extension Bool {
var intValue: Int {
return self ? 1 : 0
}
}
let (twos, threes) = input
.map { $0.characterCounts.values }
.map { ($0.contains(2).intValue, $0.contains(3).intValue) }
.reduce((0, 0)) { ($0.0 + $1.0, $0.1 + $1.1) }
print(twos * threes)
// Part 2
extension String {
func removingCharacter(at index: Index) -> String {
var temp = self
temp.removeSubrange(index...index)
return temp
}
}
func differences(s1: String, s2: String) -> Int {
return zip(s1, s2).filter { $0.0 != $0.1 }.count
}
func combine(s1: String, s2: String) -> String {
let index = s1.indices.firstIndex { s1[$0] != s2[$0] }!
return s1.removingCharacter(at: index)
}
outside: for currentIndex in input.indices {
for candidateIndex in (currentIndex+1..<input.endIndex) {
let current = input[currentIndex]
let candidate = input[candidateIndex]
if differences(s1: current, s2: candidate) == 1 {
print(combine(s1: current, s2: candidate))
break outside
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment