I have two arrays and I want to find the index of the items that have the most addition and subtraction. for example:
var arrayA = new int[] { 1, -2, 3, 4, 15, 7, 9, 2 };
var arrayB = new int[] { 6, 7, 8, 9, 10, 12, 11 };
I want the output to be as follows:
SUM: value: 27, index of A: 4, index of B: 5
SUBTRACT: value: 14, index of A: 1, index of B: 5
I can do this by using a loop over two arrays
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());
Is this the right solution? Is there a better way?
CodePudding user response:
If you sort the arrays with index, there is no need for loop over two arrays. You choose the largest of each array
for 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, index of A: 4, index of B: 5
To subtract
, compare the largest item from arrayA with the smallest item from arrayB
(or largest item from arrayB with the smallest item from 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);
SUBTRACT: 14, index of A: 1, index of B: 5