我有一個家庭作業,我完全卡住了(level:beginner)。如何從數組中的某個點找到3個最接近的座標Java
我必須創建一個方法,可以從用戶條目和數組中的所有點中找到3個最近的距離 - 並且我卡在這裏。
的方法是: 公共靜態INT [] troisPlusProches(INT的x,INT Y,INT [] coordonneesHabitations) 其中int x和詮釋y是用戶條目,並且陣列INT [] coordonneesHabitations爲int [] coordonneesHabitations = {9,30,18,8,3,18,25,36}。 (9,30),(18,8),(3,18)和(25,36)。我使用公式:距離= 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;
}
關於此任務:我的第三個任務是創建一個方法,找到從用戶輸入3米最接近的距離,所有的點在一個數組中 - 我現在在這裏呆了兩天。鑑於這是一項家庭作業,好的建議是對其進行強力編碼,然後進行優化。所以給定一個用戶條目找到每個其他點的距離,然後排序並取3個最小值。 – mba12
我會發布我在下一個答案中所做的,這幾乎是我一直在做的事情。但是我沒有得到第二和第三距離的結果。我試圖把它放在一個循環中,我嘗試了3個獨立的循環(如下面的例子)。我試圖在一個循環內循環......但仍然沒有結果;( – Frenchie
)在查找第二個和第三個點之前,您需要將'minDistance'重置爲'Float.MAX_VALUE',否則它將永遠找不到任何東西,因爲所有點比老的最小距離更大的距離 – nhouser9