ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 평행
    코딩 테스트/Level 0 2022. 11. 8. 15:15
    반응형

    https://school.programmers.co.kr/learn/courses/30/lessons/120875

     

    프로그래머스

    코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

    programmers.co.kr

     

    분수의 덧셈과 유사한 문제.

    파이썬 

    파이썬 built-in 라이브러리를 사용하면 아주 쉽게 풀 수 있다.

    '평행하다'는 말은 '기울기가 같다'는 말이다.

    선분의 기울기는 'y 증가량 / x 증가량'이며 
    증가량은 A, B의 x 좌표, y 좌표끼리의 뺄셈으로 구할 수 있다.  

    기울기를 기약분수 형태로 set에 저장하면서 겹침을 체크했다.

    (지문이 바뀌어 아래의 코드로 통과가 되지 않습니다.)

    from itertools import combinations
    from fractions import Fraction
    
    
    def solution(dots):
        temp = set()
        for dot1, dot2 in combinations(dots, 2):
            inclination = Fraction(dot1[1] - dot2[1], dot1[0] - dot2[0])
            if inclination in temp:
                return 1
            temp.add(inclination)
        return 0

    겹치지 않는 2점을 선택해서 선분을 그어야 한다는 조건이 추가되었다.

    def solution(dots):
        (x1, y1), (x2, y2), (x3, y3), (x4, y4) = dots
        return 1 if ((y1 - y2) * (x3 - x4) == (y3 - y4) * (x1 - x2)) or \
                    ((y1 - y3) * (x2 - x4) == (y2 - y4) * (x1 - x3)) or \
                    ((y1 - y4) * (x2 - x3) == (y2 - y3) * (x1 - x4)) else 0

    코틀린

    class Solution {
        fun solution(dots: Array<IntArray>): Int {
            return if (
                (dots[0][0] - dots[1][0]) * (dots[2][1] - dots[3][1]) ==
                (dots[2][0] - dots[3][0]) * (dots[0][1] - dots[1][1]) ||
                (dots[1][0] - dots[2][0]) * (dots[3][1] - dots[0][1]) ==
                (dots[3][0] - dots[0][0]) * (dots[1][1] - dots[2][1]) ||
                (dots[0][0] - dots[2][0]) * (dots[1][1] - dots[3][1]) ==
                (dots[1][0] - dots[3][0]) * (dots[0][1] - dots[2][1])
            ) 1 else 0
        }
    }
    반응형
Designed by Tistory.