Sum of products of two arrays (dotproduct)

前端 未结 6 1348
难免孤独
难免孤独 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:13

    Solutions with LINQ

    int[] digits1 = new int[10]{0,1,2,3,4,5,6,7,8,9};
    int[] digits2 = new int[10]{0,1,2,3,4,5,6,7,8,9};
    
    int result1 = digits1.Zip(digits2, (x, y) => x * y).Sum();
    
    int result2 = digits1.Select((x, y) => x * digits2.ElementAt(y)).Sum();
    
    int result3 = digits1.Select((n, i) => n * digits2[i]).Sum();
    
    // Ani answer
    int result4 = Enumerable.Range(0, digits1.Length)
        .Sum(i => digits1[i] * digits2[i]);
    

    Performance test 100000 iterations:

    Queries
    Fn: Result 1       Ticks 135306
    Fn: Result 2       Ticks 2470614
    Fn: Result 3       Ticks 130034
    Fn: Result 4       Ticks 123374
    
    -------------
    
    Fastest
    Fn: Result 4       Ticks 123374
    Fn: Result 3       Ticks 130034
    Fn: Result 1       Ticks 135306
    Fn: Result 2       Ticks 2470614
    

提交回复
热议问题