两个数组的积(数量积) [英] Sum of products of two arrays (dotproduct)

查看:165
本文介绍了两个数组的积(数量积)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先,我知道我的标题可以制定更好的,但我的数学课都这么远了我不记得正确的话了..

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..

我需要做的是这样的(伪C#)

I need to do something like this (pseudo c#)

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 result = digits1*digits2

此将每个阵列的元素[I]的产物的总和。

This would be the sum of the product of element[i] of each array.

这显然是行不通的。
无论是走向一个更好的标题或解决方案有什么建议?

This obviously doesn't work. Any suggestions towards either a better title or the solution?

修改
澄清:我知道我可以循环他们两个和做数学题。
基本上我想有一个更好的办法做到这一点,我纯粹是寻找它出于个人好奇。

EDIT clarification: I know I could loop them both and do the math. Basically I would think there is a better way to do this and I'm looking for it purely out of personal curiousity.

推荐答案

使用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("...");

编辑:
杰夫M个点了, Enumerable.Zip 只添加到.NET 4.0框架。在.NET 3.5中,你可以这样做(这个想法是唯一有效的,揭露的快速索引集合):

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();

这篇关于两个数组的积(数量积)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆