본문 바로가기

알고리즘/프로그래머스

[프로그래머스]Lv2. 교점에 별 만들기(Python)

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

 

프로그래머스

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

programmers.co.kr

 

문제 접근 

 

<사고의 흐름 정리> => 코드 구현 전(까먹을까 봐;;)

  1. 두 직선이 가능한 관계와 조건 
    1. 만나거나
      • 2, 3이 아니면 무조건 만난다. 
    2. 평행하거나
      • A1 / A2  ==  B1 / B2
    3. 일치한다.
      • A1 / A2 == B1 / B2 == C1 / C2
  2. 그럼 만나는 경우 교점은?
    1. X의 계수(A)나 Y의 계수(B)가 하나라도 0인 경우 0이 아닌 계수의 숫자를 동일하게 맞춰서 교점을 구한다.
    2. 둘 다 0이 아닌 경우 A 또는 B 둘 중 아무거나 선택 
  3.  교점이 정수 여부 판단 후 정수가 아니면 배제
  4. 교점의 바운더리 체크
    • 교점을 순회하면서 x의 min, max 과 y의 min, max를 구해서 별찍기 

<오답>

참고 사항 보면서 다시 품.. 아 참고 사항 안 읽고 식 구하려고 혼자 끙끙댄 거 생각하면ㅠㅠ 

=> 주어지지 않았다면 상당히 어려웠을 문제

 

코드

 

교점 구하는 부분에서 너무 많은 시간 소요.. (45분 넘..) 조건을 다 분기하는게 맞나 의심..

def solution(line):
    answer = []
    
    for i in range(len(line)):
        for j in range(i, len(line), 1):
            if line[i][0] == 0 and line[j][0] != 0:  # 교점의 Y값 먼저 구하기
                y =  (line[i][2] / line[i][1]) * (-1)
                x = (y - line[j][2]) / line[j][0]
            elif line[i][0] != 0 and line[j][0] == 0:   # 교점의 Y값 먼저 구하기 
                y = (line[j][2] / line[j][1]) * (-1)
                x = (y - line[i][2]) / lind[i][0]
            elif line[i][1] == 0 and line[j][1] != 0:
                x = (line[i][2] / line[i][0]) * (-1)
                y = ((-x) - line[j][2]) / line[j][1]
            elif line[j][1] == 0 and line[i][1] != 0:
                x = (line[j][2] / line[j][0]) * (-1)
                y = ((-x) - line[i][2]) / line[i][1]
            else:

 

def solution(line):
    answer = []
    
    nodes = []
    
    for i in range(len(line)):
        a, b, e = line[i]
        for j in range(i+1, len(line)):
            c, d, f = line[j]
            # 두 직선이 평행 or 일치
            if a*d - b*c == 0:
                continue
            # 두 직선이 교점을 가질 때 + 정수일 때
            elif (b*f - e*d) / (a*d - b*c) == int((b*f - e*d) / (a*d - b*c)) and (e*c- a*f) / (a*d - b*c) == int((e*c - a*f) / (a*d - b*c)):
                x = int((b*f - e*d) / (a*d - b*c))
                y = int((e*c - a*f) / (a*d - b*c))
                nodes.append((x,y))
    nodes = list(set(nodes))  # 중복 제거(간과)
    
    x_nodes = []
    y_nodes = []
    
    for i in nodes:
        x_nodes.append(i[0])
        y_nodes.append(i[1])
        
    x_min = min(x_nodes)
    x_max = max(x_nodes)
    y_min = min(y_nodes)
    y_max = max(y_nodes)
    
    coordinates = [['.' for _ in range(x_min,x_max+1)] for _ in range(y_min,y_max+1)]
    
    for i in nodes:
        x = i[0] - x_min
        y = y_max - i[1]
        coordinates[y][x] = '*' # x가 열, y는 행
        
    for i in coordinates:   # 합쳐서 출력
        answer.append(''.join(i))
    
    return answer