Skip to content

Instantly share code, notes, and snippets.

@Gryzor
Created December 18, 2015 01:24
Show Gist options
  • Save Gryzor/d141825a7b6548b3bf14 to your computer and use it in GitHub Desktop.
Save Gryzor/d141825a7b6548b3bf14 to your computer and use it in GitHub Desktop.
import Swift
/*
Now, a nice string is one with all of the following properties:
It contains a pair of any two letters that appears at least twice in the string without overlapping, like xyxy (xy) or aabcdefgaa (aa), but not like aaa (aa, but it overlaps).
It contains at least one letter which repeats with exactly one letter between them, like xyx, abcdefeghi (efe), or even aaa.
*/
var d5input: [String] = ["qjhvvvzxzqqjkmpb", "sknufchjdvccccta", "ugqblsonqaxycvkg", "yevmbiyrqdqrmlbw", "bvpvwrhoyneorcmm", "gbyjqzcsheaxnyib", "knhsmdjssycvuoqf","nizjxiwdakpfttyh", "nwrkbhorhfqqoliz", "ynsqwvwuwzqpzzwp", "yitscrgexjfclwwh", "dhajwxqdbtrfltzz", "bmrfylxhthiaozpv", "frvatcvgknjhcndw", "xlvtdmpvkpcnmhya", "pxpemuzuqzjlmtoc", "dijdacfteteypkoq", "knrcdkrvywagglnf", "viuajtspnvnptia", "xvlqzukmwbcjgwho"]
var pairs = [String:Int]()
func day5_2(input: [String]) {
var good = 0
for str in input {
if (checkString(str)) {
print("good one: \(str)")
good++
}
}
print("\n Found \(good) good string(s)")
}
func checkString(s: String) -> Bool {
var isCheckOneOK: Bool = false
var isCheckTwoOK: Bool = false
var isAtEnd: Bool = false
pairs.removeAll()
for var pos = 0 ; pos < s.characters.count - 1 ; pos++ {
let char = String(s[s.startIndex.advancedBy(pos)])
var pair = ""
pair += char
pair += String(s[s.startIndex.advancedBy(pos + 1)])
// Check 1 (Non Overlapping Pairs)
if (pairs.keys.contains(pair)) {
if let pairStartingPos = pairs[pair] {
if pairStartingPos == pos - 1 {
// overlaps, bail out
print("Skipping String \(s) because pair \(pair) is duplicated and overlaps at position \(pairStartingPos)")
return false
}
else {
isCheckOneOK = true
}
}
} else {
pairs[pair] = pos
}
// Check 2 At least one letter repeats with something in between
if (pos+2) > s.characters.count - 1 {
isAtEnd = true
}
if isAtEnd {
continue
}
let charPlusTwo: String? = String(s[s.startIndex.advancedBy(pos + 2)])
if (charPlusTwo != nil) {
if char == charPlusTwo {
isCheckTwoOK = true
}
}
}
return isCheckOneOK && isCheckTwoOK
}
day5_2(d5input)
@Gryzor
Copy link
Author

Gryzor commented Dec 18, 2015

By "manually" looking at the input I used, it seems right.

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