저장을 습관화

프로그래머스 LV.0 길이에 따른 연산 본문

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

프로그래머스 LV.0 길이에 따른 연산

ctrs 2023. 9. 14. 23:14

프로그래머스 LV.0 길이에 따른 연산

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

 

프로그래머스

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

programmers.co.kr

 

1. 문제 명

길이에 따른 연산


2. 문제 설명

정수가 담긴 리스트 num_list가 주어질 때, 리스트의 길이가 11 이상이면 리스트에 있는 모든 원소의 합을 10 이하이면 모든 원소의 곱을 return하도록 solution 함수를 완성해주세요.


3. 제한 사항

- 2 ≤ num_list의 길이 ≤ 20

- 1 ≤ num_list의 원소 ≤ 9


4. 예시

num_list result
[3, 4, 5, 2, 5, 4, 6, 7, 3, 7, 2, 2, 1] 51
[2, 3, 4, 5] 120


5. 기본 제공 코드

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


6. 제출한 내 답

const solution = (num_list) => {
  return num_list.length >= 11
    ? num_list.reduce((a, b) => {
        return a + b;
      })
    : num_list.reduce((a, b) => {
        return a * b;
      });
};

 

6-2. VSC에 작성한 내용

const solution = (num_list) => {
  // let sum = num_list.reduce((a, b) => {
  //   return a + b;
  // });

  // let mul = num_list.reduce((a, b) => {
  //   return a * b;
  // });

  return num_list.length >= 11
    ? num_list.reduce((a, b) => {
        return a + b;
      })
    : num_list.reduce((a, b) => {
        return a * b;
      });
};

// 테스트
console.log(solution([3, 4, 5, 2, 5, 4, 6, 7, 3, 7, 2, 2, 1]));
console.log(solution([2, 3, 4, 5]));


7. 특이사항

없음


8. 다른 사람이 작성한 답

8-1. 

const solution = (n) => n.reduce((a, v) => (n.length > 10 ? a + v : a * v));

와 reduce 안에 삼항연산자를 넣을 수도 있구나