Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- var str = "hhhhh Hello playground"
- extension String {
- static func groupBy(_ string: String, _ f: (Character, Character) -> Bool) -> [String] {
- let array = Array(string) as! [Character]
- let groups = Array.groupBy(array, f)
- return groups.map { g in String(g) }
- }
- static func group(_ string: String) -> [String] {
- return groupBy(string) { (leftChar, rightChar) in leftChar == rightChar }
- }
- }
- extension Array {
- static func groupBy(_ array: [Element] , _ f: (Element, Element) -> Bool) -> [[Element]] {
- guard let firstChar = array.first else {
- return []
- }
- let (left, right) = Array.span(array, { c in f(firstChar, c) })
- return [left] + groupBy(right, f)
- }
- static func span(_ array: [Element], _ pred: (Element) -> Bool) -> ([Element], [Element]) {
- if array.isEmpty {
- return ([], [])
- }
- let right = Array(array.drop(while: pred))
- let left = Array(array.prefix(while: pred))
- return (left, right)
- }
- func groupBy(_ f: (Element, Element) -> Bool) -> [[Element]] {
- return Array.groupBy(self, f)
- }
- }
- extension Array where Element: Equatable {
- static func group(_ array: [Element]) -> [[Element]] {
- return groupBy(array as! [Element]) { (leftElem, rightElem) in leftElem == rightElem }
- }
- func group() -> [[Element]] {
- return Array.group(self)
- }
- }
- let group = String.group(str)
- print("Group string: \(group) \n")
- let group1 = Array.group([1,2,5,5,5,6,7,7])
- print("Group array: \(group1)\n")
- let span1 = Array.span([1,1,1,2,2,2], { e in e != 2} )
- print("Span array: \(span1)")
Add Comment
Please, Sign In to add comment