Advertisement
Alexxik

Untitled

Mar 18th, 2024
229
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Swift 1.11 KB | None | 0 0
  1. // MARK: - Скалярное произведение сжатых векторов
  2.  
  3. struct CompressedBlock {
  4.     var value: Int64
  5.     var count: Int
  6. }
  7.  
  8. func dotProduct(lhs: [CompressedBlock], rhs: [CompressedBlock]) -> Int64 {
  9.     var result: Int64 = 0
  10.  
  11.     var lhsBlock = CompressedBlock(value: 0, count: 0)
  12.     var rhsBlock = CompressedBlock(value: 0, count: 0)
  13.  
  14.     var lhsIndex = 0
  15.     var rhsIndex = 0
  16.  
  17.     while lhsIndex < lhs.count || rhsIndex < rhs.count {
  18.         if lhsBlock.count == 0 {
  19.             lhsBlock = lhs[lhsIndex]
  20.             lhsIndex += 1
  21.         }
  22.         if rhsBlock.count == 0 {
  23.             rhsBlock = rhs[rhsIndex]
  24.             rhsIndex += 1
  25.         }
  26.  
  27.         let commonCount = min(lhsBlock.count, rhsBlock.count)
  28.         result += Int64(commonCount) * lhsBlock.value * rhsBlock.value
  29.         lhsBlock.count -= commonCount
  30.         rhsBlock.count -= commonCount
  31.     }
  32.  
  33.     return result
  34. }
  35.  
  36. let vectorA = [CompressedBlock(value: 1, count: 3)]
  37. let vectorB = [CompressedBlock(value: 1, count: 2), CompressedBlock(value: 10, count: 1)]
  38.  
  39. dotProduct(lhs: vectorA, rhs: vectorB)
  40.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement