Level
프로그래머스 Lv4
Day
22일
kakao
2019 카카오 블라인드
 
function solution(food_times, k) {
    var answer = 0;
    
    let size = food_times.length
		// 순서를 저장하며 sort
    const foods = food_times.map((food, i) => ({food, i}))
                            .sort((a,b) => a.food - b.food)
            
    let i=0
    while(i< foods.length){
        // 음식 회전이 몇 번 되면 0인 음식이 발생하는지 (회전수)
        let nth = foods[i].food - (foods[i-1] || {food:0}).food

				// 어떤 음식이 동나기 전에 종료될 경우
        if(k < size * nth){
            const remains = foods.slice(i).sort((a,b) => a.i -b.i)
            return remains[k % size].i+1
        }
        
        k -= size * nth
 
실패 코드 ( 효율성 2 실패)
 
function solution(food_times, k) {
    var answer = 0;
    
    let size = food_times.length
    food_times = food_times.map((food, i) => ({food, i}))
        .sort((a,b) => a.food - b.food)
            
    for(let i=0; i<food_times.length; i++){
        let nth = food_times[i].food - (food_times[i-1] || {food:0}).food

        while(nth){
            if(k < size){
                const remains = food_times.slice(i).sort((a,b) => a.i -b.i)
                return remains[k].i+1
            }
            
            k -= size
            nth--
        }
        size--
    }
    
    return -1;
}
 
효율성 2 실패
 
function solution(food_times, k) {
    var answer = 0;
    
    let size = food_times.length
    food_times = food_times.map((food, i) => ({food, i}))
        .sort((a,b) => a.food - b.food)
            
    for(let i=0; i<food_times.length; i++){
        let nth = food_times[i].food - (food_times[i-1] || {food:0}).food

        if(k - nth * size < 0){
            while(nth>0){
                if(k < size){
                    const remains = food_times.slice(i).sort((a,b) => a.i -b.i)
                    return remains[k].i+1
                }

                k -= size
                nth--
            }
        }else{
            k -= size * nth
        }
        
        size--
    }
    
    return -1;
}