迭代器的元素明智乘法和计算和

问题描述

使用两个列表,可以按以下方式计算这些列表的元素明智乘法和结果列表的总和。

{
    "_pipeline": [
        {
            "$match": {
                "entityId": "5eb658d7"
            }
        },{
            "$lookup": {
                "from": "entity","localField": "_id","foriegnField": "entityId","as": "rating"
            }
        },{
            "$group": {
                "_id": null,"avg": {
                    "$avg": "$rating"
                }
            }
        }
    ],"options": {}
}

如何以最佳,快速的方式在Scala中为两个迭代器执行此操作?

解决方法

(iterator1 zip iterator2).foldLeft(0.0) { case (a,(b,c)) => a + b * c }

我想很好。如果您想从中挤出最后的性能,请使用数组和while循环。

,

您可以使用适用于任何集合和任何数字类型的这段代码。
它试图通过一次遍历完成所有事情来提高效率。但是,就像@Martijn所说的那样,如果您需要它成为最有效的解决方案,则只需使用原始类型如 Int Double 的普通 Arrays >和一个while

def dotProduct[N : Numeric](l1: IterableOnce[N],l2: IterableOnce[N]): N =
  l1.iterator.zip(l2).map {
    case (x,y) => Numeric[N].times(x,y)
  }.sum

(注意:此代码适用于2.13+,对于2.12-,您可以使用 Iterable 代替 IterableOnce