我有一个家庭作业,我完全卡住了(级别:初学者)。
我必须创建一个方法来找到距用户条目和数组中所有点最近的 3 个距离 - 我被困在这里。
方法是:public static int[] troisPlusProches(int x, int y, int[] coordonneesHabitations) 其中int x和int y是用户条目,数组int[] coordonneesHabitations是int[] coordonneesHabitations = {9, 30, 18、8、3、18、25、36}。所以点是(9,30),(18,8),(3,18)和(25,36)。
我使用公式:distance = Math.sqrt(((x1 - x2) * (x1 - x2)) + ((y1 - y2) * (y1 - y2))) 来计算距离。
现在我必须从用户条目中找到 3 个最短距离,并将它们的位置返回到一个新数组中。
因此,如果用户条目是 x=10,则 y=15。
最短的距离是距点 (3, 18) 的 7.616,下一个是距点 (18, 8) 的 10.630,第三个是距点 (9, 30) 的 15.033。在这种情况下,该方法应返回一个数组 int[] troisPlusProches = {3, 18, 18, 8, 9, 30}。
我知道我必须做什么,我只是不知道如何...
这是许多错误尝试之一:
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;
}