Created
January 23, 2019 14:40
-
-
Save nerdsupremacist/20a5d30d1312772ce4494c9449a3ca35 to your computer and use it in GitHub Desktop.
LargestSevenSegmentDisplayableWords
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
enum ComparisonResult { | |
case equal | |
case larger | |
case smaller | |
} | |
extension Comparable { | |
static func ~= (lhs: Self, rhs: Self) -> ComparisonResult { | |
if lhs == rhs { | |
return .equal | |
} else if lhs < rhs { | |
return .larger | |
} else { | |
return .smaller | |
} | |
} | |
} | |
extension Sequence { | |
func filter(by keyPath: KeyPath<Element, Bool>) -> [Element] { | |
return filter { $0[keyPath: keyPath] } | |
} | |
func max(by compare: (Element, Element) throws -> ComparisonResult) rethrows -> [Element] { | |
return try reduce([]) { results, element in | |
guard let previous = results.last else { return [element] } | |
switch try compare(previous, element) { | |
case .equal: | |
return results + [element] | |
case .larger: | |
return [element] | |
case .smaller: | |
return results | |
} | |
} | |
} | |
func max<Property: Comparable>(by transformation: (Element) throws -> Property) rethrows -> [Element] { | |
return try max { | |
let (lhs, rhs) = (try transformation($0), try transformation($1)) | |
return lhs ~= rhs | |
} | |
} | |
func max<Property: Comparable>(by keyPath: KeyPath<Element, Property>) -> [Element] { | |
return max { $0[keyPath: keyPath] } | |
} | |
} | |
extension String { | |
var range: NSRange { | |
return NSRange(startIndex..<endIndex, in: self) | |
} | |
var isSevenSegmentDisplayable: Bool { | |
return self ~= "^[^gkmqvwxzio]*$" | |
} | |
} | |
extension String { | |
static func ~= (lhs: String, rhs: String) -> Bool { | |
let regularExpression = try! NSRegularExpression(pattern: rhs) | |
return regularExpression.numberOfMatches(in: lhs, options: [], range: lhs.range) > 0 | |
} | |
} | |
let words = ["a", "ab", "abc", "cde", "what"] // for demo purposes | |
let longest: [String] = words.filter(by: \.isSevenSegmentDisplayable).max(by: \.count) | |
print(longest) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment