문제: 코딩테스트 연습 - 평행 | 프로그래머스 스쿨 (programmers.co.kr)
문제설명
점 네 개의 좌표를 담은 이차원 배열 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 |
나의 문제 풀이
class Solution {
public int solution(int[][] dots) {
int answer = 0;
int x1 = dots[0][0], y1 = dots[0][1];
int x2 = dots[1][0], y2 = dots[1][1];
int x3 = dots[2][0], y3 = dots[2][1];
int x4 = dots[3][0], y4 = dots[3][1];
double line1 = (double) (y2 - y1) / (x2 - x1);
double line2 = (double) (y4 - y3) / (x4 - x3);
if (line1 == line2) answer = 1;
line1 = (double) (y3 - y1) / (x3 - x1);
line2 = (double) (y2 - y4) / (x2 - x4);
if (line1 == line2) answer = 1;
line1 = (double) (y4 - y1) / (x4 - x1);
line2 = (double) (y2 - y3) / (x2 - x3);
if (line1 == line2) answer = 1;
return answer;
}
}
다른 사람의 문제풀이
//다른사람 풀이1
class Solution {
public double 기울기구하기(int [] dot1, int [] dot2) {
System.out.println((double)(dot2[1] - dot1[1]) / (dot2[0] - dot1[0]));
return (double) (dot2[1] - dot1[1]) / (dot2[0] - dot1[0]);
}
public int solution(int[][] dots) {
int answer = 0 ;
if(기울기구하기(dots[0], dots[1]) == 기울기구하기(dots[2], dots[3])) return 1;
if(기울기구하기(dots[0], dots[2]) == 기울기구하기(dots[1], dots[3])) return 1;
if(기울기구하기(dots[0], dots[3]) == 기울기구하기(dots[1], dots[2])) return 1;
return answer;
}
}
//다른사람 풀이2
class Solution {
int[][] dots;
public int solution(int[][] dots) {
this.dots = dots;
if (parallel(0, 1, 2, 3)) return 1;
if (parallel(0, 2, 1, 3)) return 1;
if (parallel(0, 3, 1, 2)) return 1;
return 0;
}
boolean parallel(int a, int b, int c, int d) {
int x = (dots[a][0] - dots[b][0]) * (dots[c][1] - dots[d][1]);
int y = (dots[a][1] - dots[b][1]) * (dots[c][0] - dots[d][0]);
return x == y || x == -y;
}
}
'코딩테스트 연습 > 프로그래머스 LV.0' 카테고리의 다른 글
[프로그래머스] Lv.0 외계어 사전 - 자바(Java) (0) | 2024.05.03 |
---|---|
[프로그래머스] Lv.0 저주의 숫자 3 - 자바(Java) (2) | 2024.05.01 |
[프로그래머스] Lv.0 겹치는 선분의 길이 - 자바(Java) (0) | 2024.04.26 |
[프로그래머스] Lv.0 유한소수 판별하기 - 자바(Java) (0) | 2024.04.25 |
[프로그래머스] Lv.0 특이한 정렬 - 자바(Java) (0) | 2024.04.23 |