두점 간의 거리 계산 예제:
Point p1 = new Point(5, 6); // 첫 번째 점의 좌표 (5,6)
Point p2 = new Point(7, 8); // 두 번째 점의 좌표 (7,8)
// 좌표값 출력
System.out.println("p1의 x 좌표: " + p1.getX());
System.out.println("p1의 y 좌표: " + p1.getY());
System.out.println("p2의 x 좌표: " + p2.getX());
System.out.println("p2의 y 좌표: " + p2.getY());
// 두 점 사이의 거리 계산
double distance = Math.sqrt(Math.pow(p1.getX() - p2.getX(), 2) + Math.pow(p1.getY() - p2.getY(), 2));
System.out.println("두 점 사이의 거리: " + distance);
두 직선의 교점좌표 계산 예제:
@Getter
@Setter
public class LineSegment {
private final Point start;
private final Point end;
public LineSegment(Point start, Point end) {
this.start = start;
this.end = end;
}
}
public static Point intersectionPoint(LineSegment seg1, LineSegment seg2) {
double x1 = seg1.start.x;
double y1 = seg1.start.y;
double x2 = seg1.end.x;
double y2 = seg1.end.y;
double x3 = seg2.start.x;
double y3 = seg2.start.y;
double x4 = seg2.end.x;
double y4 = seg2.end.y;
double denominator = (x1 - x2) * (y3 - y4) - (y1 - y2) * (x3 - x4);
if (denominator == 0) return null;
double x = ((x1 * y2 - y1 * x2) * (x3 - x4) - (x1 * y2 - y1 * x2) * (y3 - y4)) / denominator;
double y = ((x1 * y2 - y1 * x2) * (y3 - y4) - (y1 * x2 - x1 * y2) * (x3 - x4)) / denominator;
if (!isBetween(x1, x2, x) || !isBetween(y1, y2, y) ||
!isBetween(x3, x4, x) || !isBetween(y3, y4, y)) {
return null;
}
return new Point(x, y);
}
private static boolean isBetween(double a, double b, double c) {
return Math.min(a, b) - 0.01 <= c && c <= Math.max(a, b) + 0.01;
}
@Test
void testIntersection() {
Point p1 = new Point(1, 1);
Point p2 = new Point(5, 5);
LineSegment seg1 = new LineSegment(p1, p2);
Point p3 = new Point(1, 5);
Point p4 = new Point(5, 1);
LineSegment seg2 = new LineSegment(p3, p4);
Point result = intersectionPoint(seg1, seg2);
System.out.println("직선 A: (1,1) ~ (5,5)");
System.out.println("직선 B: (1,5) ~ (5,1)");
System.out.println("교점: " + result);
}
특정점이 직선상에 있는지 여부 검증:
@Getter
@Setter
public class LineVO {
private final Point start;
private final Point end;
public LineVO(Point start, Point end) {
this.start = start;
this.end = end;
}
}
public static boolean isPointOnLine(LineVO line, Point point) {
double x = point.x;
double y = point.y;
double x1 = line.start.x;
double y1 = line.start.y;
double x2 = line.end.x;
double y2 = line.end.y;
// 직선 방정식을 활용한 검증
return (Math.abs((x - x1) * (y2 - y1) - (y - y1) * (x2 - x1)) < 1e-8) &&
(Math.min(x1, x2) - 0.01 <= x && x <= Math.max(x1, x2) + 0.01) &&
(Math.min(y1, y2) - 0.01 <= y && y <= Math.max(y1, y2) + 0.01);
}
@Test
void testLineCheck() {
Point start = new Point(19, 25);
Point end = new Point(19, 30);
LineVO lineVO = new LineVO(start, end);
Point testPoint = new Point(19, 26);
boolean result = isPointOnLine(lineVO, testPoint);
System.out.println("점 (19,26)이 직선상에 위치하는지: " + result);
}