Skip to content

Instantly share code, notes, and snippets.

@Palleas
Created December 4, 2017 20:42
Show Gist options
  • Select an option

  • Save Palleas/7984f0804c3b0d87e802e37d02fca0e2 to your computer and use it in GitHub Desktop.

Select an option

Save Palleas/7984f0804c3b0d87e802e37d02fca0e2 to your computer and use it in GitHub Desktop.
//: Playground - noun: a place where people can play
import Cocoa
let source = """
...
"""
func hasDuplicates(_ line: String) -> Bool {
return line.components(separatedBy: " ")
.reduce(into: [String: Int](), { result, word in
if let count = result[word] {
result[word] = count + 1
} else {
result[word] = 1
}
})
.reduce(false, { result, group in
return result || group.value > 1
})
}
hasDuplicates("aa bb cc dd ee")
hasDuplicates("aa bb cc dd aa")
hasDuplicates("aa bb cc dd aaa")
func letters(from word: String) -> [Character] {
var result = [Character]()
for letter in word {
result.append(letter)
}
return result
}
func containsAnagrams(_ line: String) -> Bool {
let allLetters = line.components(separatedBy: " ")
.map(letters)
.map { String($0.sorted()) }
let uniqueSize = Set<String>(allLetters).count
let originalSize = allLetters.count
return uniqueSize != originalSize
}
containsAnagrams("abcde fghij") // valid -> false
containsAnagrams("abcde xyz ecdab") // invalid -> true
containsAnagrams("a ab abc abd abf abj") // valid -> false
containsAnagrams("iiii oiii ooii oooi oooo") // valid -> false
containsAnagrams("oiii ioii iioi iiio") // invalid -> true
enum Result {
case valid
case hasDuplicates
case hasAnagrams
}
func isValid(_ line: String) -> Result {
guard !hasDuplicates(line) else { return .hasDuplicates }
guard !containsAnagrams(line) else { return .hasAnagrams }
return .valid
}
isValid("abcde fghij") // valid
isValid("abcde xyz ecdab") // invalid
isValid("a ab abc abd abf abj") // valid
isValid("iiii oiii ooii oooi oooo") // valid
isValid("oiii ioii iioi iiio") // invalid
source
.components(separatedBy: "\n")
.map(isValid)
.filter { $0 == .valid }
.count
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment