c# - 如何对两个列表/数组正确执行算术运算
问题描述
我有2Arrays
需要执行算术运算的双打(+、-、/、*)
Array1 = d1 , d2, d3, d4, d5, d6, , , d9, d10
Array2 = d3, d4, , d6, , d8, d9, d10
Operation = "+";
Edit Above Empty 元素的显示只是为了表示它们都存储的数据,没有空格
Array1 = d1, d2, d3, d4, d5, d6, d9, d10
Array2 = d3, d4, d6, d8, d9, d10
请求输出
ArrayOpt =
[0] = d3+d3
[1] = d4+d4;
[2] = d5+d4;
[3] = d6+d6;
[4] = d6+d8;
[5] = d9+d9;
[6] = d10+d10;
我试过的
int i = 0, PreviousIndex = -1;
int SecondaryIndex = 0;
// check if there is a gap
if (SecondaryIndex < DATES2.Length && Convert.ToInt32(d) != Convert.ToInt32(DATES2[SecondaryIndex]))
{
// first value of index contain the index of second symbol date that matches with first symbol's first date.
// eg: first data => d1 d2 d3 d4 d5 d6
// 2nd data => d3 d4 d6
// in the above case, the index would be the index of d3.
index = DATES2.Select((v, j) => new { Index = j, Value = (int)v }).Where(p => p.Value == (int)d).Select(p => p.Index).ToList();
if (index.Count > 0)
SecondaryIndex = index[0];
else
SecondaryIndex = -1;
}
if(secondaryIndex != -1)
{
CalculateData(operation, DATES1[i],DATES2[secondaryIndex]);
PreviousIndex = secondaryIndex;
}
else
{
CalculateData(operation, DATES1[i],DATES2[PreviousIndex]);
}
i++;
secondaryIndex++;
但输出是这样的
d1, d2, d3, d4, d5, d6, d9, d10
+
d3, d4, d6, d8, d9, d10
任何人都可以提出问题或任何其他更好的解决方案吗?
解决方案
您可以使用Math.Net库来执行基本的线性代数运算和所有您可能想要使用的矩阵运算。正如您在链接中看到的基本线性代数运算示例所示(+、*、-、/)。
此外,由于您的矩阵是一维的,因此您可以使用单个 for 循环对 Array1 和 Array2 索引求和,如下所示。
var a1 = new int[5] {1,2,3,4,5};
var a2 = new int[7] {1,2,3,4,5,6,7};
var maxLength = a1.Length > a2.Length ? a1.Length : a2.Length;
var outputArray = new int[maxLength];
for(var i = 0; i < maxLength; i++)
{
if(a1.Length < i + 1)
{
outputArray[i] = a2[i];
continue;
}
if(a2.Length < i + 1)
{
outputArray[i] = a1[i];
continue;
}
outputArray[i] = a1[i] + a2[i];
}
Console.Write(outputArray.GetValue(6));
推荐阅读
- jenkins - 哪种 ANT 风格的路径模式可以在 JenkinsFile 中捕获 foo_1.23.456_bar.baz 但不能捕获 foo_1.23.456_qux_bar.baz?
- java - 在java中打印2个日期之间的所有日期,特殊情况
- hyperledger - 运行超级账本 iroha 的快速启动版本和构建 iroha 有什么区别?
- azure-api-management - Azure - API 管理 - 管理 API SAS 令牌到期
- linear-programming - In Scipy Linprog, is there a setting that makes the results "nicer"?
- c++ - 我可以将 CFMutableDictionaryRef 转换为 CFDictionaryRef 吗?
- javascript - 使用 jquery 或 js 刷新所有浏览器选项卡
- android - 如何以编程方式从 Firebase 获取无崩溃用户的百分比
- django - 如何在 Azure Kubernetes 服务上向公众隐藏 Django 管理员,同时通过后门保持访问
- c# - 在 Asp.net 核心 Web API 中使用 Continuation 令牌的正确方法是什么