STUDY/알고리즘

[프로그래머스] 당구 연습 (javascript)

디리릭 2023. 9. 10. 15:30
728x90

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

 

프로그래머스

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

programmers.co.kr

 

이 문제에서의 당구 공은 입사각과 반사각이 같다. 따라서 원쿠션 포인트 기점으로 시작 공과의 기울기와 타겟 공과의 기울기 크키는 같고 방향만 다르다. 

 

그래서 둘 중 하나의 공의 위치를 대칭 이동하면 두 공의 거리 같과 공이 이동한 거리와 같다. 

 

function solution(m, n, startX, startY, balls) {
    const start = [startX,startY];
    const answer = balls.map(p=>{
        const points = getReflectPoint(m,n,start,p);
        const ds = points.map(p=>calculDistence(p[0],p[1]));
        
        return Math.min(...ds);
    });
    
    return answer;
}

function getReflectPoint(m,n,start, end){
    const points = [];
    const [x1,y1] = start;
    const [x2,y2] = end;
    
    //x축 대칭
    if(x1 !== x2 || y1 < y2){
        points.push([[x1,y1],[x2,y2*-1]])
    }
    //y축 대칭
    if(y1 !== y2 || x1 < x2){
        points.push([[x1,y1],[x2*-1,y2]])
    }
    //y=n 대칭
    if(x1 !== x2 || y1 > y2){
        points.push([[x1,y1],[x2,2*n -y2]])
    }
    //x=m 대칭
    if(y1 !== y2 || x1 > x2){
        points.push([[x1,y1],[2*m-x2,y2]])
    }
    
    return points;
}

function calculDistence(start,end){
    const [x1,y1] = start;
    const [x2,y2] = end;
    
    return Math.pow(x1-x2,2) + Math.pow(y1-y2,2);
}
728x90