Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // MARK: - Скалярное произведение сжатых векторов
- struct CompressedBlock {
- var value: Int64
- var count: Int
- }
- func dotProduct(lhs: [CompressedBlock], rhs: [CompressedBlock]) -> Int64 {
- var result: Int64 = 0
- var lhsBlock = CompressedBlock(value: 0, count: 0)
- var rhsBlock = CompressedBlock(value: 0, count: 0)
- var lhsIndex = 0
- var rhsIndex = 0
- while lhsIndex < lhs.count || rhsIndex < rhs.count {
- if lhsBlock.count == 0 {
- lhsBlock = lhs[lhsIndex]
- lhsIndex += 1
- }
- if rhsBlock.count == 0 {
- rhsBlock = rhs[rhsIndex]
- rhsIndex += 1
- }
- let commonCount = min(lhsBlock.count, rhsBlock.count)
- result += Int64(commonCount) * lhsBlock.value * rhsBlock.value
- lhsBlock.count -= commonCount
- rhsBlock.count -= commonCount
- }
- return result
- }
- let vectorA = [CompressedBlock(value: 1, count: 3)]
- let vectorB = [CompressedBlock(value: 1, count: 2), CompressedBlock(value: 10, count: 1)]
- dotProduct(lhs: vectorA, rhs: vectorB)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement