저장을 습관화

프로그래머스 LV.0 삼각형의 완성조건 (1) 본문

코딩 테스트/프로그래머스 - 자바스크립트

프로그래머스 LV.0 삼각형의 완성조건 (1)

ctrs 2023. 9. 14. 23:01

프로그래머스 LV.0 삼각형의 완성조건 (1)

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

 

프로그래머스

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

programmers.co.kr

 

1. 문제 명

삼각형의 완성조건 (1)


2. 문제 설명

선분 세 개로 삼각형을 만들기 위해서는 다음과 같은 조건을 만족해야 합니다.

 

- 가장 긴 변의 길이는 다른 두 변의 길이의 합보다 작아야 합니다.

 

삼각형의 세 변의 길이가 담긴 배열 sides이 매개변수로 주어집니다. 세 변으로 삼각형을 만들 수 있다면 1, 만들 수 없다면 2를 return하도록 solution 함수를 완성해주세요.


3. 제한 사항

- sides의 원소는 자연수입니다.

- sides의 길이는 3입니다.

- 1 ≤ sides의 원소 ≤ 1,000


4. 예시

sides result
[1, 2, 3] 2
[3, 6, 2] 2
[199, 72, 222] 1


5. 기본 제공 코드

function solution(sides) {
    var answer = 0;
    return answer;
}


6. 제출한 내 답

const solution = (sides) => {
  let max = Math.max(...sides);

  let others = sides.reduce((a, b) => {
    return a + b;
  }, 0);

  return max < others - max ? 1 : 2;
};

 

6-2. VSC에 작성한 내용

const solution = (sides) => {
  // 가장 긴 변의 길이
  let max = Math.max(...sides);
  // console.log(`max는 ${max}`);

  // 다른 두 변의 길이의 합
  let others = sides.reduce((a, b) => {
    return a + b;
  }, 0);

  // console.log(`others는 ${others}`);

  return max < others - max ? 1 : 2;
};

// 테스트
console.log(solution([1, 2, 3]));
console.log(solution([3, 6, 2]));
console.log(solution([199, 72, 222]));


7. 특이사항

처음 시도했던 방법

const solution = (sides) => {
  // 가장 긴 변의 길이
  let max = Math.max(...sides);
  
  // 다른 두 변의 길이의 합
  let others = sides
    .filter((element) => element < max)
    .reduce((a, b) => {
      return a + b;
    }, 0);

  return max < others ? 1 : 2;
};

// 테스트
console.log(solution([1, 2, 3]));
console.log(solution([3, 6, 2]));
console.log(solution([199, 72, 222]));

테스트에서는 통과했으나 채점에서 틀렸다

왜 그럴까 생각해보니까 이등변 삼각형의 경우를 빠져있었다

 

만약 배열이 [7, 7, 5] 였다면

filter, reduce 과정에서 7이 모두 탈락해 5만 남게 된다.

5만 남아서는 가장 큰 변의 길이인 7보다 클 수가 없게되는데,

 

작성된 코드에서 이는 max < others에서 거짓이 되어버린다.

 

다른 방법이 있을까 질문하기를 살펴봤는데 아래와 같은 내용이 있었다.


8. 다른 사람이 작성한 답

8-1. 배열 오름차순

function solution(sides) {
    sides = sides.sort((a,b) => a-b)
    return sides[0]+sides[1] > sides[2] ? 1 : 2;
}

배열의 요소를 오름차순으로 정렬하고, 아래 두 요소를 더한값과 가장 큰 요소를 비교

 

8-2. 나와 비슷하게 한 사람

function solution(sides) {
    var answer = 0;
    const max = Math.max(...sides);
    const sum = sides.reduce((a,b) => a + b, 0) - max;

    answer = max < sum? 1 : 2;

    return answer;
}

 

8-3. 내림차순

function solution(sides) {
    const [long, a, b] = sides.sort((a,b) => b-a);

    return long < a + b ? 1 : 2


}

 

 

정답률 89% 문제인데 이렇게 오래 걸리기까지 하면서 틀리다니