728x90
반응형
SMALL

문제 설명

점 네 개의 좌표를 담은 이차원 배열  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

  • 점을 어떻게 연결해도 평행하지 않습니다.
class Solution {
    public int solution(int[][] dots) {
        int answer = 0;

        double slope1 = (double) (dots[1][1] - dots[0][1]) / (dots[1][0] - dots[0][0]);
        double slope2 = (double) (dots[3][1] - dots[2][1]) / (dots[3][0] - dots[2][0]);
        double slope3 = (double) (dots[2][1] - dots[0][1]) / (dots[2][0] - dots[0][0]);
        double slope4 = (double) (dots[3][1] - dots[1][1]) / (dots[3][0] - dots[1][0]);

        if (Math.abs(slope1 - slope2) < 1e-9 || Math.abs(slope1 - slope4) < 1e-9 || Math.abs(slope3 - slope2) < 1e-9) {
            answer = 1;
        }

        return answer;
    }
}

테스트 5, 12, 13, 16 실패..ㅠㅠ

계속해서 안되서 질문하기를 통해 답을 얻었습니다!

개인적인 의견은 문제 출제자분께서 조금 더 명확하게 문제를 설명하지 않았기 때문에 생긴 상황이라고 생각합니다.

4개의 점을 각각 a,b,c,d라고 했을 때, 12번 케이스부터 틀리신 분들은 아마 아래와 같은 6가지 경우의 수를 생각하셨을 겁니다.

  • a-b, a-c, a-d, b-c, b-d, c-d

그런데 문제에 적혀있는 '주어진 네 개의 점을 두 개씩 이었을 때'를 다시 잘 곱씹어보면서 혹시 아래와 같은 3가지 경우의 수 만을 의미하는게 아닌가 하고 코드를 처음부터 다시 짜보았고 통과했습니다.

  • [a-b, c-d],[a-c, b-d],[a-d, b-c]

즉, 4개의 점들로 임의의 두 쌍을 만들었을 때 그 두 쌍이 이루는 직선이 서로 평행한지를 묻는 문제였습니다.

정말.. 감사합니다!!

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

- [[x1, y1], [x2, y2], [x3, y3], [x4, y4]]

주어진 네 개의 점을 두 개씩 이었을 때, 두 직선이 평행이 되는 경우가 있으면 1을 없으면 0을 return 하도록 solution 함수를 완성해보세요.
 */
public class H120875 {
	public int solution(int[][] dots) {
		int answer = 0;

		double[] slopes = new double[3];
		slopes[0] = (double) (dots[1][1] - dots[0][1]) / (dots[1][0] - dots[0][0]) - (double) (dots[3][1] - dots[2][1]) / (dots[3][0] - dots[2][0]);
		slopes[1] = (double) (dots[2][1] - dots[0][1]) / (dots[2][0] - dots[0][0]) - (double) (dots[3][1] - dots[1][1]) / (dots[3][0] - dots[1][0]);
		slopes[2] = (double) (dots[2][1] - dots[1][1]) / (dots[2][0] - dots[1][0]) - (double) (dots[3][1] - dots[0][1]) / (dots[3][0] - dots[0][0]);

		for (double slope : slopes) {
			if (Math.abs(slope) < 1e-9) {
				answer = 1;
				break;
			}
		}

		return answer;
	}
}

하루종일 걸렸네요..

다른사람의 풀이

import java.lang.Math;
class Solution {
    private int xPos = 0;
    private int yPos = 1;
    private int[][] checkCases = {{0, 1, 2, 3}, {0, 2, 1, 3}, {0, 3, 1, 2}};
    public int solution(int[][] dots) {
        int answer = 0;
        for (int[] checkCase : checkCases) {
            if (checkParallel(checkCase, dots)) {
                answer = 1;
                break;
            }
        }

        return answer;
    }

    private boolean checkParallel(int[] checkCase, int[][] dots) {
        int xPos1 = dots[checkCase[0]][xPos];
        int yPos1 = dots[checkCase[0]][yPos];
        int xPos2 = dots[checkCase[1]][xPos];
        int yPos2 = dots[checkCase[1]][yPos];
        int xPos3 = dots[checkCase[2]][xPos];
        int yPos3 = dots[checkCase[2]][yPos];
        int xPos4 = dots[checkCase[3]][xPos];
        int yPos4 = dots[checkCase[3]][yPos];
        // (y4 - y3)(x2 - x1) - (x4 - x3)(y2 - y1) 평행여부 조건
        int chk = ((yPos4 - yPos3) * (xPos2 - xPos1)) - ((xPos4 - xPos3) * (yPos2 - yPos1));
        if (chk == 0) {
            return true;
        }
        return false;
    }
}
import java.util.HashMap;
import java.util.Map;

class Solution {
    public int solution(int[][] dots) {

        Map<Double, Double> straightInfoMap = new HashMap<>();

        for (int i = 0; i < dots.length - 1; i++) {
            for (int j = i + 1; j < dots.length; j++) {
                double slope = Math.abs((double) (dots[j][1] - dots[i][1]) / (double) (dots[j][0] - dots[i][0]));
                double y_intercept =  ((double) (dots[j][1]) - slope * dots[j][0]);
                if (straightInfoMap.containsKey(slope) && straightInfoMap.get(slope) != y_intercept)
                    return 1;
                straightInfoMap.put(slope, y_intercept);
            }
        }

        System.out.println(straightInfoMap);

        return 0;
    }
}

역시 알고리즘은.. 풀이가 너무 많아요..

항상다른사람의 풀이를 통해 배우고 갑니다!! 오늘은 코드 리뷰로 채울 생각!!

저도 HashMap으로 잘 풀고 싶은데.. 아직 이걸 제대로 이해하지 못해서 제대로 활용한 게 손에 꼽히네요 ㅠㅠ

728x90
반응형
LIST

'알고리즘 > 프로그래머스 JAVA LV.0' 카테고리의 다른 글

왼쪽 오른쪽  (0) 2023.05.07
주사위 게임 3  (0) 2023.05.07
배열 만들기 4  (0) 2023.05.06
배열 만들기 6  (0) 2023.05.06
문자열 출력하기  (0) 2023.05.06

+ Recent posts