Sum of products of two arrays (dotproduct)

前端 未结 6 1365
难免孤独
难免孤独 2021-02-04 05:49

First off, I know my title can be formulated better, but my math classes are so far gone I can\'t remember the correct words anymore..

I need to do something like this (

6条回答
  •  渐次进展
    2021-02-04 06:34

    With LINQ:

    int dotProduct = digits1.Zip(digits2, (d1, d2) => d1 * d2)
                            .Sum();
    

    Zipwill produce a streaming sequence containing the products of corresponding elements from both arrays, which is then summed into an integer with Sum.

    Note that this will not fail like it should when the arrays of unequal length, so you probably need to validate the input:

    //null checks here
    
    if(digits1.Length != digits2.Length)
       throw new ArgumentException("...");
    

    EDIT: As Jeff M points out,Enumerable.Zipwas only added to the framework in .NET 4.0. In .NET 3.5, you can do this (the idea is only efficient for collections that expose fast indexers):

    int dotProduct = Enumerable.Range(0, digits1.Length)
                               .Sum(i => digits1[i] * digits2[i]);
    
    //from Jeff M's comment:
    int dotProduct = digits1.Select((n, i) => n * digits2[i])
                            .Sum();
    

提交回复
热议问题