Skip to content

Instantly share code, notes, and snippets.

@felix-larsen
Created December 2, 2020 07:27
Show Gist options
  • Save felix-larsen/d6d97c3da8ff9d239b4aafdd346074b2 to your computer and use it in GitHub Desktop.
Save felix-larsen/d6d97c3da8ff9d239b4aafdd346074b2 to your computer and use it in GitHub Desktop.
2nd December solution - Advent of Code 2020
let validPasswordsCount = passwords
.map { password -> DataEntry in
let substrings = password.split(separator: " ")
let minMaxSub = substrings[0].split(separator: "-")
return DataEntry(min: Int(minMaxSub[0])!, max: Int(minMaxSub[1])!, char: substrings[1].first!, password: String(substrings[2]))
}
.filter(isValid_1)
.count
print(validPasswordsCount)
func isValid_1(entry: DataEntry) -> Bool {
let occurrences = entry.password.countOccurrencesOf(char: entry.char)
return occurrences >= entry.min && occurrences <= entry.max
}
let validPasswordsCount = passwords
.map { password -> DataEntry in
let substrings = password.split(separator: " ")
let minMaxSub = substrings[0].split(separator: "-")
return DataEntry(min: Int(minMaxSub[0])!, max: Int(minMaxSub[1])!, char: substrings[1].first!, password: String(substrings[2]))
}
.filter(isValid_2)
.count
print(validPasswordsCount)
func isValid_2(entry: DataEntry) -> Bool {
let pos1valid = entry.password.charAt(entry.min-1) == entry.char
let pos2valid = entry.password.charAt(entry.max-1) == entry.char
return pos1valid != pos2valid
}
struct DataEntry {
let min: Int
let max: Int
let char: Character
let password: String
}
extension String {
func countOccurrencesOf(char: Character) -> Int {
return self.components(separatedBy: String(char)).count - 1
}
func charAt(_ i: Int) -> Character {
return Array(self)[i]
}
}
let passwords: [String] = [
"2-4 p: vpkpp",
"6-16 b: bbbbbbbbbbbbbbbpb",
"6-7 z: zzfzzdz"]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment