728x90
문제 설명
점 네 개의 좌표를 담은 이차원 배열 dots가 다음과 같이 매개변수로 주어집니다.
- [[x1, y1], [x2, y2], [x3, y3], [x4, y4]]
주어진 네 개의 점을 두 개씩 이었을 때, 두 직선이 평행이 되는 경우가 있으면 1을 없으면 0을 return 하도록 solution 함수를 완성해보세요.
제한사항
- dots의 길이 = 4
- dots의 원소는 [x, y] 형태이며 x, y는 정수입니다.
- 0 ≤ x, y ≤ 100
- 서로 다른 두개 이상의 점이 겹치는 경우는 없습니다.
- 두 직선이 겹치는 경우(일치하는 경우)에도 1을 return 해주세요.
- 임의의 두 점을 이은 직선이 x축 또는 y축과 평행한 경우는 주어지지 않습니다.
입출력 예
dots | result |
[[1, 4], [9, 2], [3, 8], [11, 6]] | 1 |
[[3, 5], [4, 1], [2, 4], [5, 10]] | 0 |
입출력 예 설명
입출력 예 #1
- 점 [1, 4], [3, 8]을 잇고 [9, 2], [11, 6]를 이으면 두 선분은 평행합니다.
입출력 예 #2
- 점을 어떻게 연결해도 평행하지 않습니다.
※ 공지 - 2022년 9월 30일 제한 사항 및 테스트 케이스가 수정되었습니다.
※ 공지 - 2022년 10월 27일 제한 사항 및 테스트 케이스가 수정되었습니다.
※ 공지 - 2023년 2월 14일 테스트 케이스가 수정되었습니다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
|
class Solution {
public int solution(int[][] dots) {
int answer = 0;
// [a-b, c-d],[a-c, b-d],[a-d, b-c] 3개의 경우만 처리함
// 기울기 = y좌표의 차이 / x좌표의 차이
// [a-b, c-d]
double inclination1 = (double)(dots[0][1]-dots[1][1]) / (dots[0][0]-dots[1][0]);
double inclination2 = (double)(dots[2][1]-dots[3][1]) / (dots[2][0]-dots[3][0]);
//System.out.println(inclination1 + ", " + inclination2);
if(inclination1==inclination2) answer = 1;
// [a-c, b-d]
inclination1 = (double)(dots[0][1]-dots[2][1]) / (dots[0][0]-dots[2][0]);
inclination2 = (double)(dots[1][1]-dots[3][1]) / (dots[1][0]-dots[3][0]);
//System.out.println(inclination1 + ", " + inclination2);
if(inclination1==inclination2) answer = 1;
// [a-d, b-c]
inclination1 = (double)(dots[0][1]-dots[3][1]) / (dots[0][0]-dots[3][0]);
inclination2 = (double)(dots[1][1]-dots[2][1]) / (dots[1][0]-dots[2][0]);
//System.out.println(inclination1 + ", " + inclination2);
if(inclination1==inclination2) answer = 1;
return answer;
}
}
|
cs |
이 문제는 테스트에 통과하기 위하여 [a-b, c-d],[a-c, b-d],[a-d, b-c] 3가지 경우만 처리한다. 문제가 조금 이상하기는 하다. 3가지의 경우 기울기를 구하여 기울기가 같으면 1을 반환하게 하였다. |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
class Solution {
public int solution(int[][] dots) {
int answer = 0;
// [a-b, c-d],[a-c, b-d],[a-d, b-c]
// [a-b, c-d]
if(inclination(dots[0], dots[1])==inclination(dots[2], dots[3])) answer = 1;
// [a-c, b-d]
if(inclination(dots[0], dots[2])==inclination(dots[1], dots[3])) answer = 1;
// [a-d, b-c]
if(inclination(dots[0], dots[3])==inclination(dots[1], dots[2])) answer = 1;
return answer;
}
// 두점의 기울기를 리턴하는 메서드
public double inclination(int[] a, int[] b) {
return (double)(a[1]-b[1]) / (a[0]-b[0]);
}
}
|
cs |
두 점의 기울기를 구하는 메서드를 만들어 사용하면 편리하다. |
728x90
'프로그래머스 코딩(자바) > Level 0' 카테고리의 다른 글
Programmers Level 0 - 옹알이 (1) (0) | 2023.03.08 |
---|---|
Programmers Level 0 - 겹치는 선분의 길이 (0) | 2023.03.08 |
Programmers Level 0 - 안전지대 (0) | 2023.03.08 |
Programmers Level 0 - 연속된 수의 합 (0) | 2023.03.07 |
Programmers Level 0 - 분수의 덧셈 (0) | 2023.03.07 |