본문 바로가기
알고리즘/Codewars

[Codewars] Sum without highest and lowest number (8 kyu) / JavaScript

by fluss 2022. 11. 14.

https://www.codewars.com/kata/576b93db1129fcf2200001e6

 

Codewars - Achieve mastery through coding practice and developer mentorship

A coding practice website for all programming levels – Join a community of over 3 million developers and improve your coding skills in over 55 programming languages!

www.codewars.com

 

DESCRIPTION:

Task

Sum all the numbers of a given array ( cq. list ), except the highest and the lowest element ( by value, not by index! ).

The highest or lowest element respectively is a single element at each edge, even if there are more than one with the same value.

Mind the input validation.

 

Example

{ 6, 2, 1, 8, 10 } => 16
{ 1, 1, 11, 2, 3 } => 6

 

Input validation

If an empty value ( null, None, Nothing etc. ) is given instead of an array, or the given array is an empty list or a list with only 1 element, return 0.

 

설명:

작업

주어진 배열(리스트)의 가장 큰 요소와 가장 작은 요소를 제외한 (인덱스가 아닌 값으로!) 모든 숫자의 합을 구하세요. 

가장 큰 또는 작은 요소는 같은 값이 하나 이상이더라도 제각기 각 끝에 있는 단일 요소입니다.

입력 유효성 검사를 염두에 두세요.

 

예시

{ 6, 2, 1, 8, 10 } => 16
{ 1, 1, 11, 2, 3 } => 6

 

입력 유효성 검사

만약 빈 값(null, None, Nothing 등)이 배열 대신 주어지거나 주어진 배열이 빈 리스트 거나 리스트가 1개의 요소만 가지고 있으면, 0을 반환합니다.

 

풀이

array가 빈 배열이거나 배열의 크기가 2보다 작을 때는 0을 반환하게 하고 배열을 정렬해서 pop과 shift로 가장 큰 값과 작은 값을 제거해준다. 그리고 배열의 모든 요소를 더한 값을 반환한다.

 

코드

function sumArray(array) {
  if(!array) return 0;
  if(array.length < 2) return 0;
  array.sort((a, b) => a - b);
  array.pop();
  array.shift();
  let result = 0;
  for(let i = 0; i < array.length; i++){
    result += array[i];
  }
  return result;
}

 

다른 사람의 좋았던 풀이

function sumArray(array) {
  return Array.isArray(array) && array.length > 1
    ? array.reduce((s, n) => s + n, 0) - Math.min(...array) - Math.max(...array)
    : 0
}

 

참고

https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Array/shift

 

Array.prototype.shift() - JavaScript | MDN

shift() 메서드는 배열에서 첫 번째 요소를 제거하고, 제거된 요소를 반환합니다. 이 메서드는 배열의 길이를 변하게 합니다.

developer.mozilla.org

 

https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Array/pop

 

Array.prototype.pop() - JavaScript | MDN

pop() 메서드는 배열에서 마지막 요소를 제거하고 그 요소를 반환합니다.

developer.mozilla.org

 

댓글