프로그래밍 기초 5일차 - 알고리즘 문제 풀기

2022. 11. 29. 20:05항해99/2주차 - 프로그래밍 기초

오늘 다 풀겠다...

진짜로...

근데 어렵다 해보자...


33. 체육복

답: 개인적으로 젤 어려웠다...

function solution(n, lost, r) {
    let a =[];
    
    lost.sort((x,y)=>x[1]-y[1]);
    r.sort((x,y)=>x-y);
    
    for(i in r)if(lost.indexOf(r[i]) ===-1)a.push(r[i]) //빌려줄 수 있는 얘들 추리기
        
    let b= lost.filter(x=>{
        for(i in r)if(r[i]===x)return false;
        return true;
    }).sort((x,y)=>x-y)  //빌려야하는 얘들 추리기
    
    for(i in b) {          
        for(j in a){        
            if((a[j]-1<=b[i])&&(a[j]+1>=b[i])){
                a[j]= -10;    // 빌린얘들 번호 -10으로 바꾸기
                b[i]= -10;    //빌려준 얘들 번호 -10으로 바꾸기
                break;
            }
        }
        if(b[i]!==-10)n--   //빌려야하는데 빌리지 못했다면 전체인원에서 -1
    }
    return n 
}

34. 포켓몬

답: 어렵게 생각안하니 이건 진짜 5분만에 풀어서 너무 좋았슴 ㅎ

function solution(nums) {
    return   [...new Set(nums)].length>nums.length/2? nums.length/2:[...new Set(nums)].length
}

35. 비밀지도

답: 비트연산자로 빠르게 했다 ㅎㅎ 처음엔 비트 연산자를 몰라서 2진수로 바꾸고 다시 10진수로 바꾸고 ...

function solution(n, arr1, arr2) {
    let result = []
   for(i=0; i<n; i++){
       result[i] = (arr1[i]|arr2[i]).toString(2)
        result[i] = "0".repeat(n - result[i].length) + result[i];
    
        result[i]= result[i].replace(/1/,'#')
        result[i]= result[i].replace(/0/,' ')
    }
       return  result
   }

36. 키패드 누르기

답:  *은 10, 0은 11 #은 12로 처리함 

function solution(n, h) {
    var answer = [];
    let left = [1,4];//* 10
    let right =[3,4];//# 12   //+3
    let point = [] 
    
    for(i in n){//[7, 0, 8, 2, 8, 3, 1, 5, 7, 6, 2], "left" "RRLLLRR" //"LRLLLRL
         if(n[i]===0)n[i]=11;
            point=[n[i]%3, Math.ceil(n[i]/3)]
        if(n[i]%3===1){
            answer.push('L')
            left=[1, Math.ceil(n[i]/3)]    //left 1,3 //riggt 3 ,4  //n[i] 2 4   2  > 1
        }else if(n[i]%3===0){
            answer.push('R')
            right=[3, Math.ceil(n[i]/3)]
        }else{

           if((Math.abs(left[0]-point[0])+Math.abs(left[1]-point[1]))>(Math.abs(right[0]-point[0])+Math.abs(right[1]-point[1]))){
               answer.push('R')
               right=[2, Math.ceil(n[i]/3)]
           }else if((Math.abs(left[0]-point[0])+Math.abs(left[1]-point[1]))<(Math.abs(right[0]-point[0])+Math.abs(right[1]-point[1]))){
               answer.push('L')
              left=[2,Math.ceil(n[i]/3)]
           }else{
               if(h==='left'){
                answer.push('L')
                 left=[2,  Math.ceil(n[i]/3)]
               }else{
                  answer.push('R')
                 right=[2,Math.ceil(n[i]/3)]
               }
           }

     }
    }
    return answer.join('')
}

37. 다트게임

답: 정규식 때문에 어려워서 그냥 내식으로 풀었다... 만약 정규식을 제대로 알았더라면 더 짧게도 가능할듯..

담에 공부해보자

function solution(dartResult) {
    let sum = [];
    let index = 0; 

    for(let i = 0; i < dartResult.length; i++){
        if(dartResult[i] === "S"){
            if((dartResult[i-2] === "1") && (dartResult[i-1] === "0")){ 
                sum.push(10**1);
            } else {
                sum.push(dartResult[i-1]**1);
            }
            index++;
        } else if (dartResult[i] === "D"){
            if((dartResult[i-2] === "1") && (dartResult[i-1] === "0")){  
                sum.push(10**2);
            } else {
                sum.push(dartResult[i-1]**2);
            }
            index++;
        } else if (dartResult[i] === "T"){
            if((dartResult[i-2] === "1") && (dartResult[i-1] === "0")){ 
                sum.push(10**3);
            } else {
                sum.push(dartResult[i-1]**3);
            }
            index++;
        } else if (dartResult[i] === "*"){
            sum[index - 1] *= 2;
            sum[index - 2] *= 2;
        } else if (dartResult[i] === "#"){
            sum[index - 1] *= (-1);
        } 
    }

    return sum.reduce((acc, curr) => acc + curr, 0);
}

38. 최댓값과 최솟값

답: 쏘이지 ㅎ

function solution(s) {
    var answer = '';
    
    let sample = s.split(' ')
     
    return `${Math.min(...sample)} ${Math.max(...sample)}`
}

39. 숫자의 표현

답:  약수중 홀수의 숫자가 답이다...(수학적으로 쉽게 접근했다 ㅎ...나름 수학영재 출신ㅎ)

function solution(n) {
    var answer = 0;
    
    for(i=0; i<=n; i++){
        if(n%i===0&&i%2===1)answer++
    }
    return answer;
}

40. 크레인 인형뽑기 게임

답: 마지막...깔끔하게 컷 ㅎ

function solution(b,m) {
    var answer = [];
    
    for(i=0;i<m.length;i++)for(j=0; j<b.length; j++)if(b[j][m[i]-1]!==0){
                answer.push(b[j][m[i]-1])
                b[j][m[i]-1]=0
                break;
            }//뽑힌 인형들 세우기
        
    
    let count =0 //사라진 갯수
    
    for(i=0;i<answer.length;i++)if(answer[i]===answer[i+1]){ //사라진 갯수 카운트 
            answer.splice(i,2)
            i=-1;
            count+=2
        }
    
    return count
}

마지막 문제까지 깔끔하게 풀었다!

하지만 지금까지 열심히 푼 문제들은 고작 레벨 1짜리들,,,

취업하려면 레벨 2~3정도는 풀어줘야 메리트가 있을 것 같다

하루에 한문제씩 꼭 풀어보자!!