[프로그래머스] 교점에 별 만들기

bej_ve·2022년 11월 1일
0

python알고리즘

목록 보기
41/46

<문제>
Ax + By + C = 0으로 표현할 수 있는 n개의 직선이 주어질 때, 이 직선의 교점 중 정수 좌표에 별을 그리려 합니다.
별이 그려진 부분은 , 빈 공간(격자선이 교차하는 지점)은 .으로 표현하면 다음과 같습니다.
"..........."
".....
....."
"..........."
"..........."
"........."
"..........."
"..........."
"..........."
"..........."
"........."
"..........."
이때 격자판은 무한히 넓으니 모든 별을 포함하는 최소한의 크기만 나타내면 됩니다.

따라서 정답은

"........"
"........."
"........."
"
......."
"........."
"........."
"........."
"........."
"
.......*"
입니다.

직선 A, B, C에 대한 정보가 담긴 배열 line이 매개변수로 주어집니다. 이때 모든 별을 포함하는 최소 사각형을 return 하도록 solution 함수를 완성해주세요.

<코드>

from itertools import combinations

def intersection_point(line1, line2):
    a,b,e=line1
    c,d,f=line2
    if a*d==b*c:
        return None
    x=(b*f-e*d)/(a*d-b*c)
    y=(e*c-a*f)/(a*d-b*c)
    if x==int(x) and y==int(y):
        return (int(x),int(y))

def solution(line):
    N=len(line)
    combs=list(combinations(line,2))
    points=set()
    for comb in combs:
        point=intersection_point(comb[0],comb[1])
        if point:
            points.add(point)
    xs=[p[0] for p in points]
    x_min=min(xs)
    x_max=max(xs)
    
    ys=[p[1] for p in points]
    y_min=min(ys)
    y_max=max(ys)
    
    answer = ['.'*(x_max-x_min+1)]*(y_max-y_min+1)
    
    for point in points:
        x,y=point
        answer[y_max-y]=answer[y_max-y][:x-x_min]+'*'+answer[y_max-y][x-x_min+1:]
    return [''.join(ans) for ans in answer]

0개의 댓글