점 네 개의 좌표를 담은 이차원 배열 dots가 다음과 같이 매개변수로 주어집니다.
[[x1, y1], [x2, y2], [x3, y3], [x4, y4]]
주어진 네 개의 점을 두 개씩 이었을 때, 두 직선이 평행이 되는 경우가 있으면 1을 없으면 0을 return 하도록 solution 함수를 완성해보세요.
제한사항
dots의 길이 = 4
dots의 원소는 [x, y] 형태이며 x, y는 정수입니다.
0 ≤ x, y ≤ 100
서로 다른 두개 이상의 점이 겹치는 경우는 없습니다.
두 직선이 겹치는 경우(일치하는 경우)에도 1을 return 해주세요.
임의의 두 점을 이은 직선이 x축 또는 y축과 평행한 경우는 주어지지 않습니다.
입출력 예
dots result
[[1, 4], [9, 2], [3, 8], [11, 6]] 1
[[3, 5], [4, 1], [2, 4], [5, 10]] 0
입출력 예 설명
입출력 예 #1
점 [1, 4], [3, 8]을 잇고 [9, 2], [11, 6]를 이으면 두 선분은 평행합니다.
입출력 예 #2
점을 어떻게 연결해도 평행하지 않습니다.
function solution(dots) {
let inclination = [];
for(let i = 0; i<dots.length; i++){
for(let j= i+1; j<dots.length; j++){
inclination.push((dots[j][1]-dots[i][1]) / (dots[j][0] - dots[i][0]));
}
}
let set_inclination = new Set(inclination);
return inclination.length != [...set_inclination].length ? 1 : 0 //둘이 같다면 중복 기울기x
}
이 문제는 두 점의 선택이 자유롭지 않고. 1,3 / 2,4 이렇게 선택되어야 한다.
function solution(dots) {
let inclination = [];
let inclination_corr = [];
for(let i = 0; i<dots.length; i++){
for(let j= i+1; j<dots.length; j++){
inclination.push((dots[j][1]-dots[i][1]) / (dots[j][0] - dots[i][0]));
inclination_corr.push([(dots[j][1]-dots[i][1]) / (dots[j][0] - dots[i][0]),i,j]);
}
}
let set_inclination = new Set(inclination);
let set_inclination_corr = new Set(inclination_corr);
console.log(set_inclination_corr)
return inclination.length != [...set_inclination].length ? inclination_corr.length != [...set_inclination_corr].length? 0: 1 : 0 //둘이 같다면 중복 기울기x
}
아래처럼 i,j 값을 추가해줘서 해보려고 했는데 잘 안된다.
기울기는 같으면서 하나라도 i,j가 겹치지 않는걸 찾으라니..
그런데 아래 코드처럼 겹칠 경우를 고려해줘도.. 윗코드와 똑같은 테스트들에서 오류가 난다???
function solution(dots) {
let inclination_corr = [];
for(let i = 0; i < dots.length; i++){
for(let j = i+1; j < dots.length; j++){
let incline = (dots[j][1]-dots[i][1]) / (dots[j][0] - dots[i][0]);
inclination_corr.push([incline, i, j]);
}
}
for(let i = 0; i < inclination_corr.length; i++){
for(let j = i+1; j < inclination_corr.length; j++){
if(inclination_corr[i][0] === inclination_corr[j][0] && inclination_corr[i][1] != inclination_corr[j][1] && inclination_corr[i][2] != inclination_corr[j][2]){
return 1; //둘이 같다면 중복 기울기x
}
}
}
return 0; //평행한 직선이 없음
<정답>
function solution(dots) {
for(let i = 0; i < 3; i++){
for(let j = i+1; j < 4; j++){
let incline1 = (dots[j][1] - dots[i][1]) / (dots[j][0] - dots[i][0]);
let otherDots = dots.filter((dot, index) => index !== i && index !== j);
let incline2 = (otherDots[1][1] - otherDots[0][1]) / (otherDots[1][0] - otherDots[0][0]);
if(incline1 === incline2) return 1;
}
}
return 0;
}
윗코드는 선택되지 않은 i,j를 필터링해서 두번째 기울기를 구한 식이라하겠다.
<두 점의 기울기 공식>
'🗃️javascript > 프로그래머스' 카테고리의 다른 글
저주의 숫자 3 (0) | 2023.08.31 |
---|---|
안전지대 (0) | 2023.08.31 |
겹치는 선분의 길이 (0) | 2023.08.31 |
폰켓몬(Lv.1)[해시의 개념을 생각해보고, 단순히 구현하자] (0) | 2023.06.20 |
K번째수(Lv.1)[sort()는 문자정렬임. 숫자 정렬도 문자열 정렬로 취급] (0) | 2023.06.20 |