프로그래밍/이산 수학(Discrete mathematics)
[알고리즘] 두 원의 위치 관계 및 판단 구현
거북고래
2023. 6. 11. 19:30
반응형
두 원의 위치 관계
0. 필요 값
- 두 원의 중심 사이의 거리(중심거리) D
- 두 원의 반지름의 합 R2 + R1
- 두 원의 반지름의 차(큰 원의 반지름 - 작은 원의 반지름) R2 - R1
1. 두 점에서 만난다.
- 반지름의 차 < 중심거리 < 반지름의 합
- (R2 - R1) < D < (R2 + R1)
2. 한 점에서 만난다.
- 중심거리 = 반지름의 합(외접한다.)
- D = (R2 + R1)
- 중심거리 = 반지름의 차(내접한다.)
- D = (R2 - R1)
3. 만나지 않는다.
- 중심거리 > 반지름의 합(두 원이 만나지 않고 한 원이 다른 원의 외부에 있다.)
- D > (R2 + R1)
- 중심거리 < 반지름의 차(두 원이 만나지 않고 한 원이 다른 원의 내부에 있다.)
- D < (R2 - R1)
- 동심원(원의 중심 좌표가 같다.)
- D = 0
4. 두 원이 겹친다.
- 중심거리 = 0, 반지름의 차 = 0
- D = 0, R2 - R1 = 0
5. 구현
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class B1002 {
public static void main(String[] args) throws IOException {
//입력 받기
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int numberOfCases = Integer.parseInt(br.readLine());
int[] testResult = new int[numberOfCases];
for(int i = 0; i < numberOfCases; i++) {
StringTokenizer st = new StringTokenizer(br.readLine());
int[] testCase = new int[6];
for (int j = 0; j < testCase.length; j++) {
testCase[j] = Integer.parseInt(st.nextToken());
}
int x1 = testCase[0];
int y1 = testCase[1];
int r1 = testCase[2];
int x2 = testCase[3];
int y2 = testCase[4];
int r2 = testCase[5];
double distance = Math.sqrt(Math.pow(Math.abs(x2 - x1), 2) + Math.pow(Math.abs(y2 - y1), 2));
int sumOfRadius = r2 + r1;
int minusOfRadius = Math.abs(r2 - r1);
if(distance == 0 && minusOfRadius == 0) {
testResult[i] = -1;
} else if(sumOfRadius == distance || minusOfRadius == distance) {
testResult[i] = 1;
} else if(sumOfRadius > distance && minusOfRadius < distance) {
testResult[i] = 2;
} else{
testResult[i] = 0;
}
}
for (int i = 0; i < testResult.length; i++) {
System.out.println(testResult[i]);
}
}
}
참고자료
반응형