I have a homework assignment that and I am completely stuck (level: beginner).
I have to create a method that finds 3 closest distances from an user entry and all the points in an array - and I am stuck here.
The method is: public static int[] troisPlusProches (int x, int y, int[] coordonneesHabitations) where int x and int y are user entries, and the array int[] coordonneesHabitations is int[] coordonneesHabitations = {9, 30, 18, 8, 3, 18, 25, 36}. So the points are (9,30), (18,8), (3,18) and (25,36).
I used the formula: distance = Math.sqrt(((x1 - x2) * (x1 - x2)) + ((y1 - y2) * (y1 - y2))) to calculate the distances.
And now i have to find 3 shortest distances from an user entries and return their positions in a new array.
So if the user entries are x=10, y=15.
The shortest distance is 7.616 from a point (3, 18), the next one is 10.630 from a point (18, 8), and the third one is 15.033 from a point (9, 30). In this case the method should return an array int[] troisPlusProches = {3, 18, 18, 8, 9, 30}.
I know what I have to do, I just can't figure out how...
Here's one of the many wrong attempts:
public static int[] troisPlusProches (int x, int y, int[] (coordonneesHabitations)
{
int [] that = Arrays.copyOf(coordonneesHabitations, coordonneesHabitations.length);
int table[] = new int[6];
double distanceA = 0.0;
double minDistance = Float.MAX_VALUE;
int a = 0;
int b = 0;
int i = 0;
double ignore = Float.MAX_VALUE;
double ignore2 = Float.MAX_VALUE;
for (i = 0; i < that.length; i += 2) {
a = that[i];
b = that[i+1];
distanceA = calculerDistance(a, b, x, y);
if (distanceA < minDistance) {
minDistance = distanceA;
table[0] = a;
table[1] = b;
}
}
ignore = minDistance;
for (i = 0; i < that.length; i += 2) {
a = that[i];
b = that[i+1];
distanceA = calculerDistance(a, b, x, y);
if (distanceA == ignore) {
continue;
}
if (distanceA < minDistance) {
minDistance = distanceA;
table[2] = a;
table[3] = b;
}
}
ignore2 = minDistance;
for (i = 0; i < that.length; i += 2) {
a = that[i];
b = that[i+1];
distanceA = calculerDistance(a, b, x, y);
if ((distanceA == ignore) || (distanceA == ignore2)) {
continue;
}
if (distanceA < minDistance) {
minDistance = distanceA;
table[2] = a;
table[3] = b;
}
}
return table;
}