[프로그래머스 -LEVEL 2 - 캐시]

정대만·2023년 6월 28일

코딩테스트

목록 보기
6/51
post-thumbnail

문제풀이

  • 유투브 에서 본 어려운방식. 완전 탐색이다.
    ( 별로 안좋다)


//유투브에서 본 어려운 방식 



function solution(cacheSize, cities) {
   var count=0;
    var new_arr= [];
  
    for(var i=0; i<cities.length; i++){
        if(new_arr.length<cacheSize){
             if(!new_arr.includes(cities[i].toLowerCase()))
                {
                 new_arr.push(cities[i].toLowerCase());
                 count+=5;
                }
            else{
                count+=1;
            }
        }
        else {
            var ccount=1;
              var push_l=[];
            var index=-1;
            var gogo_index=i-1;
            if(new_arr.includes(cities[i].toLowerCase())){
         count+=1;
}
else{


            while(ccount<=cacheSize-1){
                if(!push_l.includes(cities[gogo_index].toLowerCase())){
                   push_l.push(cities[gogo_index].toLowerCase());
                     ccount+=1;
                   }
                 gogo_index-=1;
            }
//console.log(push_l)
          for(var ii=0; ii<new_arr.length; ii++){
              if(!push_l.includes(new_arr[ii])){
                  index=ii;
                  break;
              }
          }
           count+=5;
           new_arr[index]=cities[i].toLowerCase();
    
        }
    }
    }
    return count;
    
}
//solution(3,["Jeju", "Pangyo", "Seoul", "NewYork", "LA", "Jeju", "Pangyo", "Seoul", "NewYork", "LA"]	)



  • 참조해서 다시 짠 코드 (훨씬 간결하다.)
function solution(cacheSize, cities) {
   
    var map_cahc=[];
    var count=0;
     const same_function= function(nara){
               var Find_index= map_cahc.indexOf(nara.toLowerCase());
                  map_cahc.splice(Find_index,1);
                   map_cahc.push(nara.toLowerCase());
                   count+=1;
     }
    
    cities.map((nara)=>{
       if(cacheSize==0){
           count+=5;
       } 
        else{
        
       if(map_cahc.length<cacheSize){
           if(!map_cahc.includes(nara.toLowerCase()))
               {
                     map_cahc.push(nara.toLowerCase());
                    count+=5;
               }
            else{
                same_function(nara)
            }
       }
        else{
            //여기는 꽉차있을때 
           if(!map_cahc.includes(nara.toLowerCase()))
               {
                     map_cahc.shift();
                      map_cahc.push(nara.toLowerCase()); 
                    count+=5;
               }
            else{
                   same_function(nara)
            }
            
        }
       
        }  
   })
    return count;
}








progresses = [1, 1, 1, 1]
speeds = [100, 50, 99, 100]

같은 로직을 써서 함수로 빼버렸다.

profile
안녕하세요

0개의 댓글