문제(출처: 프로그래머스)
주어진 네 개의 점을 두 개씩 이었을 때, 두 직선이 평행이 되는 경우가 있으면 1을 없으면 0을 return 하도록 solution 함수를 완성해보세요.
▶ 내가 푼 방식
function solution(dots) {
const [[x1, y1], [x2, y2], [x3, y3], [x4, y4]] = dots
if ((Math.abs(y2-y1)/Math.abs(x2-x1)) === (Math.abs(y3-y4)/Math.abs(x3-x4))) return 1
if ((Math.abs(y3-y1)/Math.abs(x3-x1)) === (Math.abs(y2-y4)/Math.abs(x2-x4))) return 1
if ((Math.abs(y4-y1)/Math.abs(x4-x1)) === (Math.abs(y2-y3)/Math.abs(x2-x3))) return 1
return 0;
}
어떻게 풀지 한참을 생각하다가 직선의 기울기를 구하고 가능한 모든 경우의 수를 다 조합해서 비교하였다.
▶ 다른 유저가 푼 방식
// 유저 1
function solution(dots) {
if (calculateSlope(dots[0], dots[1]) === calculateSlope(dots[2], dots[3]))
return 1;
if (calculateSlope(dots[0], dots[2]) === calculateSlope(dots[1], dots[3]))
return 1;
if (calculateSlope(dots[0], dots[3]) === calculateSlope(dots[1], dots[2]))
return 1;
return 0;
}
function calculateSlope(arr1, arr2) {
return (arr2[1] - arr1[1]) / (arr2[0] - arr1[0]);
}
▶ 배운 것들
-
-