I have two arrays of doubles. For example: {1,2,3} {4,5,6} We are using (x,y) coordinates as (1,4),(2,5) and (3,6) for example. So there are 3 data points in this example. We need to calculate the slope between all of the points and store the slope with the maximum absolute value. To do this I have a function with a 'for' loop inside a 'for' loop. My code is successfully calculating the maximum absolute value slope when I use it in the Main.
So now the final step is to store the positions that this max slope occurs at in the first array and print out the values of the same positions in the second array.
NOTE: My code is printing out the values one position before where it should be. For example, if the max slope occurs at the 4th and 5th positions, then my code prints out the 3rd and 4th positions.
using System;
using System.Collections.Generic;
public class Test
{
public static void Main()
{
List<double> Array1 = new List<double>();
List<double> Array2 = new List<double>();
Array1.Add(Convert.ToDouble(columns[0]));
Array2.Add(Convert.ToDouble(columns[1]));
int[] positions = GreatestSlopeLocation(Array1, Array2);
Console.WriteLine("The Location of the max slope is {0} {1}",
Array2[positions[0]], Array2[positions[1]]);
}
static int[] GreatestSlopeLocation(List<double> x, List<double> y)
{
int size = x.Count;
double maxSlope = Double.MinValue; // don't set this to 0
// consider case when all slopes are negative
//
int index1 = 0;
int index2 = 0;
for (int i = 0; i < size; i++)
{
for (int j = i + 1; j < size; j++)
{
double slope = (y[j] - y[i]) / (x[j] - x[i]);
if (slope > maxSlope) // I think you want > instead of < here
{
maxSlope = slope;
index1 = i;
index2 = j;
}
}
}
return new int[]{index1, index2};
}
}
If I understand it correctly, your current code will always finish with i == size - 2, j==size - 1
... because every slope is greater than double.MinValue
, which is the only value that maxSlope
ever takes.
The problem is here:
if (slope > maxSlope)
{
slope = maxSlope;
index1 = i;
index2 = j;
}
If you've found a new maximum slope, you remember the indexes of it... but not the slope itself. You're assigning a new value to the slope
variable, which is never used again in that iteration. You want to remember the new maximum slope in maxSlope
:
maxSlope = slope;
See more on this question at Stackoverflow