Skip to content

Instantly share code, notes, and snippets.

@kingseungil
Created September 4, 2023 13:28
Show Gist options
  • Save kingseungil/5b9d807951961593f31c8868e7b7948f to your computer and use it in GitHub Desktop.
Save kingseungil/5b9d807951961593f31c8868e7b7948f to your computer and use it in GitHub Desktop.
package surprise_assignment;
import java.util.Arrays;
import java.util.Scanner;
public class Coordinate {
private int myX;
private int myY;
private int[][] coordinates;
public Coordinate() {
coordinates = new int[10][2];
}
public void inputMyCoordinates() {
Scanner sc = new Scanner(System.in);
System.out.print("내 좌표 x값을 입력해 주세요: ");
myX = sc.nextInt();
System.out.print("내 좌표 y값을 입력해 주세요: ");
myY = sc.nextInt();
System.out.println("나의 좌표값은 (" + myX + ", " + myY + ") 입니다.");
System.out.println();
}
public void inputRandomCoordinates() {
int count = 0;
Scanner sc = new Scanner(System.in);
while (count < 10) {
System.out.printf("%d/%d 번째 좌표값을 입력해 주세요.\n", count + 1, 10);
System.out.print("임의의 좌표 x값을 입력해 주세요: ");
int x = sc.nextInt();
System.out.print("임의의 좌표 y값을 입력해 주세요: ");
int y = sc.nextInt();
System.out.println("입력하신 좌표값은 (" + x + ", " + y + ") 입니다.");
System.out.println();
boolean isDuplicate = checkDuplicateCoordinates(x, y, count);
if (!isDuplicate) {
coordinates[count][0] = x;
coordinates[count][1] = y;
count++;
} else {
System.out.println("중복된 좌표값이 있습니다. 다시 입력해 주세요.");
System.out.println("내 좌표 값 : (" + myX + ", " + myY + ")");
System.out.println("현재 입력한 좌표 목록 : " + Arrays.deepToString(coordinates) + "\n");
}
}
}
private boolean checkDuplicateCoordinates(int x, int y, int count) {
if (x == myX && y == myY) {
return true;
} else {
for (int i = 0; i < count; i++) {
if (coordinates[i][0] == x && coordinates[i][1] == y) {
return true;
}
}
}
return false;
}
public void findClosestCoordinate() {
double minDistance = Double.MAX_VALUE;
int minIndex = 0;
for (int i = 0; i < coordinates.length; i++) {
double distance = getDistance(myX, myY, coordinates[i][0], coordinates[i][1]);
System.out.printf("(%d, %d) => %.6f\n", coordinates[i][0], coordinates[i][1], distance);
if (distance < minDistance) {
minDistance = distance;
minIndex = i;
}
}
System.out.printf("가장 가까운 좌표: \n" +
"(%d, %d) => %.6f\n", coordinates[minIndex][0], coordinates[minIndex][1], minDistance);
}
private double getDistance(int x1, int y1, int x2, int y2) {
return Math.sqrt(Math.pow((x2 - x1), 2) + Math.pow((y2 - y1), 2));
}
public static void main(String[] args) {
Coordinate coordinate = new Coordinate();
coordinate.inputMyCoordinates();
coordinate.inputRandomCoordinates();
coordinate.findClosestCoordinate();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment