프로그래머스

자바스크립트 k 번째 수

늘곰's 2023. 9. 11. 21:35
// k번쨰 수


// 문제해결
// array 를 2번째부터 5번째 까지 자름 command[0] -1  command[1]
// sort 로 자른 배열을 순서대로 정렬
// 자른배열 new arr 에서 [2] - 1 을 정답 배열에 push

//트러블 슈팅
// sort에서 특정한 조건은 주지 않아도 낮은수부터 배열이 되어서 시도해봤지만 하나의 경우에서 실패 
// 다시 sort의 오름차순 정렬로 코드를 작성하니 성공이됨
// 실패이유 sort 를 바로 쓴다면 [1,10,11,5,6,7] 같은 배열에선 sort에 아무것도 입력하지 않으면
// 정렬했을때 5,6,7 보다 10,11 이 앞에 오게 정렬이됨
function solution(array, commands) {
    var answer = [];
    

    for(let i=0; i<commands.length; i++){  
        //console.log(commands[i][0])
       var newArr = array.slice(commands[i][0]-1 , commands[i][1]).sort((a,b) => a-b);
        //console.log(newArr)
         answer.push(newArr[commands[i][2]-1])
    }
    return answer;
}



console.log(solution([1,5,2,6,3,7,4],[[2,5,3],[4,4,1],[1,7,3]]))