我有兩個陣列,我想找到加法和減法最多的專案的索引。例如:
var arrayA = new int[] { 1, -2, 3, 4, 15, 7, 9, 2 };
var arrayB = new int[] { 6, 7, 8, 9, 10, 12, 11 };
我希望輸出如下:
SUM: value: 27, index of A: 4, index of B: 5
SUBTRACT: value: 14, index of A: 1, index of B: 5
我可以通過在兩個陣列上使用回圈來做到這一點
int SUM=-1000;
int IndexA = 0;
int IndexB = 0;
for (int i = 0; i < arrayA.Count(); i )
for (int j = 0; j < arrayB.Count(); j )
{
if(arrayA[i] arrayB[j] > SUM)
{
SUM = arrayA[i] arrayB[j];
IndexA = i;
IndexB = j;
}
}
Console.WriteLine("SUM: value: " SUM.ToString() ", index of A: "
IndexA.ToString() ", index of B: " IndexB.ToString());
int SUBTRACT = -1000;
int _IndexA = 0;
int _IndexB = 0;
for (int i = 0; i < arrayA.Count(); i )
for (int j = 0; j < arrayB.Count(); j )
{
if (arrayA[i] - arrayB[j] > SUBTRACT)
{
SUBTRACT = arrayA[i] - arrayB[j];
_IndexA = i;
_IndexB = j;
}
if ( arrayB[j] - arrayA[i] > SUBTRACT)
{
SUBTRACT = arrayB[j] - arrayA[i];
_IndexA = i;
_IndexB = j;
}
}
Console.WriteLine("SUBTRACT: value: " SUBTRACT.ToString() ", index of A: " _IndexA.ToString() ", index of B: " _IndexB.ToString());
這是正確的解決方案嗎?有沒有更好的辦法?
uj5u.com熱心網友回復:
如果使用索引對陣列進行排序,則不需要對兩個陣列進行回圈。你choose the largest of each array為SUM:
var ListA = arrayA.Select((x, i) => new { value = x, Index = i }).OrderBy(x=>x.value).ToList();
var ListB = arrayB.Select((x, i) => new { value = x, Index = i }).OrderBy(x=>x.value).ToList();
Console.WriteLine("SUM:{0}, index of A: {1}, index of B: {2}", ListA[ListA.Count - 1].value
ListB[ListB.Count - 1].value, ListA[ListA.Count - 1].Index, ListB[ListB.Count - 1].Index);
SUM:27,A 指數:4,B 指數:5
要subtract,比較largest item from arrayA with the smallest item from arrayB(或來自 arrayB 的最大專案與來自 arrayA 的最小專案):
if ((ListA[ListA.Count - 1].value - ListB[0].value) >= (ListB[ListB.Count - 1].value - ListA[0].value))
Console.WriteLine("SUBTRACT: {0}, index of A: {1}, index of B: {2}", ListA[ListA.Count - 1].value - ListB[0].value, ListA[ListA.Count - 1].Index, ListB[0].Index);
else
Console.WriteLine("SUBTRACT: {0}, index of A: {1}, index of B: {2}", ListB[ListB.Count - 1].value - ListA[0].value, ListA[0].Index, ListB[ListB.Count - 1].Index);
減法:14,A 指數:1,B 指數:5
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/524200.html
