[프로그래머스] 삼각형의 완성조건 (2)

stella·2023년 1월 10일
0

Algorithm

목록 보기
13/40
post-thumbnail

문제

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

가장 긴 변의 길이는 다른 두 변의 길이의 합보다 작아야 합니다.
삼각형의 두 변의 길이가 담긴 배열 sides이 매개변수로 주어집니다. 나머지 한 변이 될 수 있는 정수의 개수를 return하도록 solution 함수를 완성해주세요.


function solution(sides) {
    const longest = Math.max(...sides); // 2
    const longestIndex = sides.indexOf(longest); // 1
    const shortIndex = longestIndex === 0 ? 1 : 0; // 0
    
    const longSide = sides[longestIndex]; // 2
    const shortSide = sides[shortIndex]; // 1
    
    let answer = (shortSide * 2) - 1; 
    
    return answer;
}

결과적으로 입력값으로 주어진 배열에서 (더 작은 값 * 2) - 1 이 정답이 된다.

따라서 이렇게 코드를 줄일 수 있게된다.

function solution(sides) {
	return Math.min(...sides) * 2 - 1;
}
profile
Frontend Engineer

0개의 댓글