나는 숙제를 할당 받았고 완전히 멈췄다 (레벨 : 초급).배열의 한 점에서 3 개의 가장 가까운 좌표를 찾는 방법 Java
사용자 항목과 배열의 모든 점에서 3 개의 가장 가까운 거리를 찾는 방법을 만들어야합니다. 여기에 붙어 있습니다.
방법은 : 공용 static INT [] troisPlusProches 을 INT (X를, INT의 예는, [] coordonneesHabitations를 INT) 여기서 INT X 및 Y는 사용자 항목이다 INT, 상기 어레이 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;
}
: 제 3 작업 방법을 작성하고 3 개 가장 근접한 사용자 항목에서 거리와 모든 포인트를 찾을 수 있습니다 배열로 - 그리고 나는 여기에서 2 일 동안 여기에서 찔 렸다. 주어진 숙제는 좋은 조언은 무차별 한 코드를 작성한 다음 나중에 최적화하는 것입니다. 그래서 사용자 입력이 각 다른 모든 점까지의 거리를 찾은 다음 정렬하고 3을 가장 작게 가져옵니다. – mba12
다음 답변에서 내가 한 것을 게시 할 예정입니다. 전체 시간 동안 수행 한 작업과 거의 같습니다. 하지만 제 2와 제 3 거리에 대한 결과는 얻지 못합니다. 하나의 루프에 넣으려고했는데, 아래의 예제처럼 3 개의 루프를 시도했습니다.루프 내에서 루프를 시도했으나 여전히 결과가 없습니다. ( – Frenchie
두 번째 및 세 번째 점을 찾기 전에'minDistance'를'Float.MAX_VALUE'로 재설정해야합니다. 그렇지 않으면 모든 점 – nhouser9