본문 바로가기

1일1알고리즘

K번째수 - 배열과 함수, sort()하면 10이 2보다 작다? | 프로그래머스 코딩테스트 [자바스크립트]

프로그래머스 코딩테스트 레벨1 문제 K번째수.

주어진 배열의 i번째 수부터 j번째 수로 이뤄진 배열을 뽑아내고 오름차순으로 정렬. 그리고 k번째 수 return.

 

function solution(array, commands) {
    let answer = [];
    
    for (let x = 0; x < commands.length; x++) {
        const i = commands[x][0];
        const j = commands[x][1];
        const k = commands[x][2];
        
        const slicedSortedArray = array.slice(i - 1, j).sort();
        
        answer.push(slicedSortedArray[k - 1]);
    }
    
    return answer;
}

 

무난하게 해결한줄 알았으나 정확성이 100%가 안 나옴.

뒤져보니 sort()에서 문제 발생. 저번에 공부한 sort()을 사용했는데 이해도가 떨어졌던 것.

 

완주하지 못한 선수 - sort(), return, break, includes, indexOf [프로그래머스 코딩테스트]

코딩테스트 연습 - 완주하지 못한 선수 수많은 마라톤 선수들이 마라톤에 참여하였습니다. 단 한 명의 선수를 제외하고는 모든 선수가 마라톤을 완주하였습니다. 마라톤에 참여한 선수들의 이��

fennecfox-dev.tistory.com

 

 

 

Array.prototype.sort()

The sort() method sorts the elements of an array in place and returns the sorted array. The default sort order is ascending, built upon converting the elements into strings, then comparing their sequences of UTF-16 code units values.

developer.mozilla.org

MDN에 따르면 The default sort order is ascending, built upon converting the elements into strings, then comparing their sequences of UTF-16 code units values.

즉 요소들을 문자열로 변환한 뒤 오름차순으로 정렬.

MDN 예시를 살펴봐도

const array1 = [1, 30, 4, 21, 100000];
array1.sort();
console.log(array1);
// expected output: Array [1, 100000, 21, 30, 4]

문자열로 변환한 다음에 정렬을 하기 때문에 '1'로 시작하는 100000을 '2'로 시작하는 21보다 작다고 뱉어냄.

 

해결방법은? sort() 안에 function을 집어넣기.

MDN에 따르면 To compare numbers instead of strings, the compare function can simply subtract b from a. The following function will sort the array in ascending order (if it doesn't contain Infinity and NaN)

 

const array1 = [1, 30, 4, 21, 100000];
array1.sort((a, b) => a - b);
console.log(array1);
// output: [1, 4, 21, 30, 100000]

 

프로그래머스 답변도

function solution(array, commands) {
    let answer = [];
    
    for (let x = 0; x < commands.length; x++) {
        const i = commands[x][0];
        const j = commands[x][1];
        const k = commands[x][2];
        
        const slicedSortedArray = array.slice(i - 1, j).sort((a, b)=> a - b);
                
        answer.push(slicedSortedArray[k - 1]);
    }
    
    return answer;
}

이렇게 바꾸니 통과.

 

sort((a, b) => a - b)는 어떤 과정을 거쳐 숫자를 오름차순으로 찍어내는 걸까.

 

역시 MDN 참고.

  • If compareFunction(a, b) returns less than 0, sort a to an index lower than b (i.e. a comes first).
  • If compareFunction(a, b) returns 0, leave a and b unchanged with respect to each other, but sorted with respect to all different elements. Note: the ECMAscript standard does not guarantee this behavior, thus, not all browsers (e.g. Mozilla versions dating back to at least 2003) respect this.
  • If compareFunction(a, b) returns greater than 0, sort b to an index lower than a (i.e. b comes first).

즉 sort()은 a - b 값이 음수면 a를 더 낮은 인덱스로, 양수면 a를 더 높은 인덱스로 지정함.

 

function compare(a, b) {
  if (a is less than b by some ordering criterion) {
    return -1;
  }
  if (a is greater than b by the ordering criterion) {
    return 1;
  }
  // a must be equal to b
  return 0;
}

뒤에서 이런 과정을 거치는 거라고 함.