Guest User

Untitled

a guest
Dec 16th, 2018
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.91 KB | None | 0 0
  1. import java.util.ArrayList;
  2. import java.util.Collections;
  3. import java.util.List;
  4. import java.util.Scanner;
  5.  
  6. /**
  7. * 좌표 정렬하기 문제<br>
  8. * 알고리즘 분류 : 정렬
  9. *
  10. * @author jayden-lee
  11. */
  12. public class Main {
  13.  
  14. public static void main(String[] args) {
  15. Scanner scanner = new Scanner(System.in);
  16.  
  17. int N = scanner.nextInt();
  18.  
  19. // 좌표 정보를 담은 객체를 관리하는 리스트
  20. List<Location> locationItems = new ArrayList<>();
  21.  
  22. for (int i = 0; i < N; i++) {
  23. int x = scanner.nextInt();
  24. int y = scanner.nextInt();
  25. locationItems.add(new Location(x, y));
  26. }
  27.  
  28. // Collections 정적 클래스의 정렬 기능 사용
  29. Collections.sort(locationItems);
  30.  
  31. for (Location location : locationItems) {
  32. System.out.println(location.x + " " + location.y);
  33. }
  34. }
  35. }
  36.  
  37. class Location implements Comparable<Location> {
  38. // 2차원 X, Y 좌표
  39. int x;
  40. int y;
  41.  
  42. public Location(int x, int y) {
  43. this.x = x;
  44. this.y = y;
  45. }
  46.  
  47. @Override
  48. public int compareTo(Location otherLocation) {
  49. // X 좌표 위치 값을 비교하기 위해서 계산한다.
  50. int compareXPositionResult = this.x - otherLocation.x;
  51.  
  52. // X 좌표 계산한 결과값이 0이 아닐 경우에만 즉시 반환한다.
  53. // 결과값이 0이라는 것은 두 개의 X 좌표가 같은 경우이므로 Y좌표 값을 계산한다.
  54. if (compareXPositionResult != 0) {
  55. return compareXPositionResult;
  56. }
  57.  
  58. // Y 좌표 계산한 결과값을 반환한다.
  59. // X, Y 좌표가 동일한 지점은 없기 때문에 따로 더 계산을 수행하지 않는다.
  60. return this.y - otherLocation.y;
  61. }
  62.  
  63. @Override
  64. public String toString() {
  65. return "Location{" +
  66. "x=" + x +
  67. ", y=" + y +
  68. '}';
  69. }
  70. }
Add Comment
Please, Sign In to add comment