본문 바로가기
🫧 코테 : CodingTest

[프로그래머스] Java : 평행

by 예옹이 2024. 4. 11.

 

문제

점 네 개의 좌표를 담은 이차원 배열  dots가 다음과 같이 매개변수로 주어집니다.

 

 

입출력 예

dots result
[[1, 4], [9, 2], [3, 8], [1, 6]] 1
[[3, 5], [4, 1], [2, 4], [5, 10]] 0

 

 


 

 

 

두 선분이 평행하다는건 두 선분의 기울기가 같다는 의미입니다.

그래서 4개의 점 중에 2개씩 뽑고, 나오는 2개의 기울기가 같은지를 비교해주면 됩니다.

 

 

1. dots[] 배열 초기화

int x1 = dots[0][0];
int y1 = dots[0][1];
int x2 = dots[1][0];
int y2 = dots[1][1];
int x3 = dots[2][0];
int y3 = dots[2][1];
int x4 = dots[3][0];
int y4 = dots[3][1];

 

 

 

2. 경우의 수 만큼 기울기 구해주기

double incl1 = (double) (y1 - y4) / (x1 - x4);
double incl2 = (double) (y2 - y3) / (x2 - x3);
if(incl1 == incl2){
	answer = 1;
}
        
double incl3 = (double) (y1 - y3) / (x1 - x3);
double incl4 = (double) (y2 - y4) / (x2 - x4);
if(incl3 == incl4){
	answer = 1;
}
        
double incl5 = (double) (y1 - y2) / (x1 - x2);
double incl6 = (double) (y3 - y4) / (x3 - x4);
if(incl5 == incl6){
	answer = 1;
}

 

 

 


 

 

 

코드

class Solution {
    public int solution(int[][] dots) {
        int answer = 0;
        
        int x1 = dots[0][0];
        int y1 = dots[0][1];
        int x2 = dots[1][0];
        int y2 = dots[1][1];
        int x3 = dots[2][0];
        int y3 = dots[2][1];
        int x4 = dots[3][0];
        int y4 = dots[3][1];
        
        double incl1 = (double) (y1 - y4) / (x1 - x4);
        double incl2 = (double) (y2 - y3) / (x2 - x3);
        if(incl1 == incl2){
            answer = 1;
        }
        
        double incl3 = (double) (y1 - y3) / (x1 - x3);
        double incl4 = (double) (y2 - y4) / (x2 - x4);
        if(incl3 == incl4){
            answer = 1;
        }
        
        double incl5 = (double) (y1 - y2) / (x1 - x2);
        double incl6 = (double) (y3 - y4) / (x3 - x4);
        if(incl5 == incl6){
            answer = 1;
        }
        
        return answer;
    }
}

 

 

 

 

 

제가 작성한 코드는 아래에서 확인하실 수 있습니다.

https://github.com/eonwy/programmers

 

GitHub - eonwy/programmers: 🔎 coding-test (programmers) 🔍

🔎 coding-test (programmers) 🔍. Contribute to eonwy/programmers development by creating an account on GitHub.

github.com