반응형

가끔은 개발을 하다보면 어떤 도형을 그려야 할 때가 있을 수 있고, 그 도형의 좌표를 시계방향으로 정렬해야 하는 상황이 올 수도 있다.

 

Convex hull 알고리즘에서도 반시계 방향으로 좌표들을 정렬한다.

https://www.crocus.co.kr/1288

 

컨벡스 헐 알고리즘(Convex Hull Algorithm)

목차 1. 컨벡스 헐 알고리즘(Convex Hull Algorithm)이란? 2. 컨벡스 헐 알고리즘(Convex Hull Algorithm) 동작 원리 3. 컨벡스 헐 알고리즘(Convex Hull Algorithm) 구현 4. 관련 문제 1. 컨벡스 헐 알고리즘(Con..

www.crocus.co.kr

 

이런 좌표들을 오름차순 / 내림차순으로 정렬하는 것이 아닌 시계방향 / 반시계방향으로 정렬하는 코드를 확인해보자.

 

 

[Sort solution : First of all, calculate the average point, and then sort everything around it by angle.]

 

import java.awt.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

public class Crocus {
    public static void main(String[] args) {
        ArrayList<Point> points = new ArrayList<>();

        points.add(new Point(5,0));
        points.add(new Point(5,15));
        points.add(new Point(0,10));
        points.add(new Point(10,10));

        System.out.println("=== Clockwise sort ===");
        sortPointsClockwise(points);
        for(Point i : points){
            System.out.println(i.x + " " + i.y);
        }

        System.out.println("=== Counter Clockwise sort ===");
        sortPointsCounterClockwise(points);
        for(Point i : points){
            System.out.println(i.x + " " + i.y);
        }

    }

    public static void sortPointsClockwise(ArrayList<Point> points) {
        float averageX = 0;
        float averageY = 0;

        for (Point point : points) {
            averageX += point.x;
            averageY += point.y;
        }

        final float finalAverageX = averageX / points.size();
        final float finalAverageY = averageY / points.size();

        Comparator<Point> comparator = (lhs, rhs) -> {
            double lhsAngle = Math.atan2(lhs.y - finalAverageY, lhs.x - finalAverageX);
            double rhsAngle = Math.atan2(rhs.y - finalAverageY, rhs.x - finalAverageX);

            // Depending on the coordinate system, you might need to reverse these two conditions
            if (lhsAngle < rhsAngle) return -1;
            if (lhsAngle > rhsAngle) return 1;

            return 0;
        };

        Collections.sort(points, comparator);
    }

    public static void sortPointsCounterClockwise(ArrayList<Point> points) {
        sortPointsClockwise(points);
        Collections.reverse(points);
    }
}

 

 

https://stackoverflow.com/questions/10460300/how-to-check-if-vertex-array-is-clockwise

 

How to check if VERTEX ARRAY is clockwise?

Solved, used this code: if ( !isClockwise(TempVectArray) ) { Collections.reverse(TempVectArray); } ... private boolean isClockwise(ArrayList arl){ Iterator it = arl.

stackoverflow.com

 

반응형