Sum without highest and lowest number

chris0205.eth·2022년 3월 9일
1

Codewars

목록 보기
5/5
post-thumbnail

Prob

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.


Answ

my

function sumArray(array) {
  if (array == null){
    return 0;
  }
  else if (array.lenght < 3){
    return 0;
  }
  else{
    array.sort(function(a,b){
      return a - b;
    });
    array.pop();
    array.shift();
    let sum = 0;
    for(i=0;i<array.length;i++){
      sum += array[i];
    }
    return sum;
  }
}

배열의 메소드 중 하나인 sort()를 이용해서 오름차순으로 배열을 정렬하고, pop()으로 가장 뒤의 값을 빼고, shift()로 가장 앞의 값을 뺐다.

sort(compareFunction(a,b))에서 compareFunction(a,b)의 리턴 값이 양수이면 b 다음 a를 위치시키고, 음수이면 a 다음 b를 위치시킨다. 그리고 0이면, 그대로 둔다.

others1

function sumArray(array) {
  if (array == null) {
    return 0;
  } else if (array.length < 2) {
    return 0;
  } else {
    array = array.sort(function(a,b) {return a - b;});
    var total = 0;
    for (var i = 1; i < array.length - 1; i++) {
      total += array[i];
    }
    return total;
  }
}

my answer과 유사하지만 노테이션에 약간의 차이가 있다. 배열의 인덱스를 1부터 시작하고 배열 마지막 인덱스 이전까지만 합을 구해서 pop(), shift()의 과정을 따로 거칠 필요가 없다.

others2

function sumArray(array) {
  
  if (array == null || array.length <= 2) {
    return 0
  }
  
  var max = Math.max.apply(Math, array);
  var min = Math.min.apply(Math, array);
  var sum = 0
  
  for (i = 0; i < array.length; i++) {
    sum += array[i];
   }

  return sum - max - min
}

Math 객체를 이용하여 풀이를 했다. array의 합을 구한후, Math를 이용해 구한 max, min을 합에서 빼주었다.

Math 객체는 수학에서 자주 사용하는 상수와 함수들을 미리 구현해 놓은 자바스크립트 표준 내장 객체이다.

apply() 메소드 : 함수를 호출하는 방법 중의 하나이다. 파라미터로 함수에서 사용할 this 객체호출하는 함수로 전달할 파라미터를 입력받는다.


마치며

배열의 다양한 메소드에 대해서 알아볼 수 있는 계기가 되었다. 배열의 다양한 메소드들과 좀 더 익숙해지도록 노력해야겠다.

profile
long life, long goal

0개의 댓글