宿題があり、完全に行き詰まっています (レベル: 初級)。
ユーザーエントリと配列内のすべてのポイントから 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、3 番目は点 (9, 30) から 15.033 です。この場合、メソッドは配列 int[] troisPlusProches = {3, 18, 18, 8, 9, 30} を返す必要があります。
やるべきことはわかっているのに、どうすればいいのかわからない…
これは多くの間違った試みの 1 つです。
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;
}