Advertisement
Alexxik

Untitled

Mar 17th, 2024
140
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Swift 1.47 KB | None | 0 0
  1. // Сложение ступенчатых графиков
  2.  
  3. struct Point {
  4.     var time: Int
  5.     var value: Int
  6. }
  7.  
  8. func sumSeries(a: [Point], b: [Point]) -> [Point] {
  9.     var result: [Point] = []
  10.     var pntA = 0
  11.     var pntB = 0
  12.     var last_a = 0
  13.     var last_b = 0
  14.  
  15.     while pntA < a.count && pntB < b.count {
  16.         if a[pntA].time < b[pntB].time {
  17.             result.append(Point(time: a[pntA].time, value: a[pntA].value + last_b))
  18.             last_a = a[pntA].value
  19.             pntA += 1
  20.         } else if a[pntA].time == b[pntB].time {
  21.             result.append(Point(time: a[pntA].time, value: a[pntA].value + b[pntB].value))
  22.             last_a = a[pntA].value
  23.             last_b = b[pntB].value
  24.             pntA += 1
  25.             pntB += 1
  26.         } else {
  27.             result.append(Point(time: b[pntB].time, value: b[pntB].value + last_a))
  28.             last_b = b[pntB].value
  29.             pntB += 1
  30.         }
  31.     }
  32.  
  33.     while pntA < a.count {
  34.         result.append(Point(time: a[pntA].time, value: a[pntA].value + last_b))
  35.         pntB += 1
  36.     }
  37.  
  38.     while pntB < b.count {
  39.         result.append(Point(time: b[pntB].time, value: b[pntB].value + last_a))
  40.         pntB += 1
  41.     }
  42.  
  43.     return result
  44. }
  45.  
  46. var result = sumSeries(a: [Point(time: 1, value: 2), Point(time: 5, value: 1)], b: [Point(time: 2, value: 4), Point(time: 3, value: 6), Point(time: 9, value: 7)])
  47. for point in result {
  48.     print("{\(point.time), \(point.value)}", terminator: " ")
  49. }
  50.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement