Guest User

Untitled

a guest
Dec 1st, 2023
41
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.11 KB | None | 0 0
  1. import Cocoa
  2.  
  3. let text = """
  4. two1nine
  5. eightwothree
  6. abcone2threexyz
  7. xtwone3four
  8. 4nineeightseven2
  9. zoneight234
  10. 7pqrstsixteen
  11. """
  12.  
  13. func getNumber(s: String) -> Int{
  14. let digits = s.filter{ $0.isNumber }
  15. if let firstDigit = digits.first {
  16. if let lastDigit = digits.last {
  17. return Int("\(firstDigit)\(lastDigit)") ?? 0
  18. }
  19. }
  20. return 0
  21. }
  22.  
  23. func convertToNumber(s: String) -> Int {
  24. let stringToNumber = ["one": 1,
  25. "two": 2,
  26. "three": 3,
  27. "four": 4,
  28. "five": 5,
  29. "six": 6,
  30. "seven": 7,
  31. "eight": 8,
  32. "nine": 9]
  33. if let digit = Int(s) {
  34. return digit
  35. } else {
  36. if let digit = stringToNumber[s] {
  37. return digit
  38. } else {
  39. print("Invalid value \(s)")
  40. return 0
  41. }
  42. }
  43. }
  44.  
  45. func findDigitsAndWords(in text: String) -> [Int] {
  46. let pattern = "\\d+|one|two|three|four|five|six|seven|eight|nine"
  47.  
  48. do {
  49. let regex = try NSRegularExpression(pattern: pattern)
  50. let matches = regex.matches(in: text, options: [], range: NSRange(text.startIndex..., in: text))
  51.  
  52.  
  53. return matches.compactMap { result in
  54. if let range = Range(result.range, in: text) {
  55. let substring = String(text[range])
  56. return convertToNumber(s: substring)
  57. }
  58. return nil
  59. }
  60. } catch {
  61. print("Invalid regex: \(error.localizedDescription)")
  62. return []
  63. }
  64. }
  65.  
  66. let fileURL = Bundle.main.url(forResource: "input_1", withExtension: "txt")
  67. let content = try String(contentsOf: fileURL!, encoding: .utf8)
  68.  
  69. var number = 0
  70.  
  71. for line in content.split(separator: "\n") {
  72. let digits = findDigitsAndWords(in: String(line))
  73. let concatenatedString = digits.map { String($0) }.joined()
  74. number += getNumber(s: concatenatedString)
  75. }
  76.  
  77. print(number)
  78.  
Add Comment
Please, Sign In to add comment