Guest User

Untitled

a guest
Jan 21st, 2018
57
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.65 KB | None | 0 0
  1. var str = "hhhhh Hello playground"
  2.  
  3. extension String {
  4. static func groupBy(_ string: String, _ f: (Character, Character) -> Bool) -> [String] {
  5. let array = Array(string) as! [Character]
  6. let groups = Array.groupBy(array, f)
  7. return groups.map { g in String(g) }
  8. }
  9.  
  10. static func group(_ string: String) -> [String] {
  11. return groupBy(string) { (leftChar, rightChar) in leftChar == rightChar }
  12. }
  13. }
  14.  
  15. extension Array {
  16. static func groupBy(_ array: [Element] , _ f: (Element, Element) -> Bool) -> [[Element]] {
  17. guard let firstChar = array.first else {
  18. return []
  19. }
  20. let (left, right) = Array.span(array, { c in f(firstChar, c) })
  21. return [left] + groupBy(right, f)
  22. }
  23.  
  24.  
  25. static func span(_ array: [Element], _ pred: (Element) -> Bool) -> ([Element], [Element]) {
  26. if array.isEmpty {
  27. return ([], [])
  28. }
  29. let right = Array(array.drop(while: pred))
  30. let left = Array(array.prefix(while: pred))
  31. return (left, right)
  32. }
  33.  
  34. func groupBy(_ f: (Element, Element) -> Bool) -> [[Element]] {
  35. return Array.groupBy(self, f)
  36. }
  37. }
  38.  
  39. extension Array where Element: Equatable {
  40. static func group(_ array: [Element]) -> [[Element]] {
  41. return groupBy(array as! [Element]) { (leftElem, rightElem) in leftElem == rightElem }
  42. }
  43.  
  44. func group() -> [[Element]] {
  45. return Array.group(self)
  46. }
  47. }
  48.  
  49. let group = String.group(str)
  50. print("Group string: \(group) \n")
  51. let group1 = Array.group([1,2,5,5,5,6,7,7])
  52. print("Group array: \(group1)\n")
  53. let span1 = Array.span([1,1,1,2,2,2], { e in e != 2} )
  54. print("Span array: \(span1)")
Add Comment
Please, Sign In to add comment