Advertisement
Alexxik

Untitled

Mar 19th, 2024 (edited)
312
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Swift 0.85 KB | None | 0 0
  1. // MARK: - Разбить массив по границам
  2.  
  3. func calculate(borders: [Int], values: [Int]) -> [(quantity: Int, sum: Int)] {
  4.     var curRangeIndex = 0
  5.     // кол-во = кол-во интервалов + 1
  6.     var res = Array(repeating: (quantity: 0, sum: 0), count: borders.count + 1)
  7.    
  8.     for value in values {
  9.        
  10.         // while нужен на случай если границы без пропусков 4 5 6
  11.         while curRangeIndex < borders.count && value > borders[curRangeIndex] {
  12.             curRangeIndex += 1
  13.         }
  14.         res[curRangeIndex].quantity += 1
  15.         res[curRangeIndex].sum += value
  16.     }
  17.    
  18.     return res
  19. }
  20.  
  21. // Пример использования:
  22. let borders = [4, 8]
  23. let values = [1, 3, 4, 5, 8, 9]
  24. let result = calculate(borders: borders, values: values)
  25. print(result)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement