프로그래머스/Level_1

[프로그래머스 Level_1 / C++ / 카카오] 키패드 누르기

배발자 2022. 2. 18.
반응형

#접근방법 

 

1.  ( '*' ,'0', '#' ) -> (10, 11, 12) 로 치환 

2.  1, 4, 7 일 때 왼손 위치 해당 값으로 이동,  3, 6, 9 일 때 오른손 위치 해당값으로 이동

3.  2, 5, 8, 11 일 때 왼손과 오른손의 위치를 중간열로 이동 (이동할때 카운트 +1, 이미 가운데에 위치했을 경우 변화 x

4.  왼손과 오른손이 위치한 숫자 값에서 가려고 하는 숫자값의 차이의 절댓값 구하기 

5.  절댓값이 더 작은 값이 나온 손에 위치 저장. 같을 경우 hand 변수에서 어떤 손잡이인지 확인하고 해당 손에 위치 저장.  

 

#include <string>
#include <vector>
#include <cmath>
using namespace std;
int temp_l, temp_r, l_cnt, r_cnt; 
string solution(vector<int> numbers, string hand) {
    string answer = "";
    int lh=10, rh=12; 
    vector <int> v = numbers; 
    for(int i=0; i<v.size(); i++){
        if(v[i]==0)v[i]=11; 
        if(v[i]==1||v[i]==4||v[i]==7){
           answer+='L';
           lh = v[i]; 
        }
        else if (v[i]==3||v[i]==6||v[i]==9){
           answer+='R'; 
           rh = v[i]; 
        }
        else{
            l_cnt=0; r_cnt=0; temp_l =lh; temp_r = rh;                
            if(lh%3==1){
                temp_l++; 
                l_cnt++; 
            }
            if(rh%3==0){
                temp_r--; 
                r_cnt++; 
            }
            if(abs(v[i]-temp_l)/3+l_cnt<abs(v[i]-temp_r)/3+r_cnt){
                answer+='L'; 
                lh = v[i]; 
            }
            else if(abs(v[i]-temp_l)/3+l_cnt>abs(v[i]-temp_r)/3+r_cnt){
                answer+='R';
                rh = v[i]; 
            }
            else{
                if(hand=="right"){
                    answer+='R'; 
                    rh = v[i]; 
                }
                else{
                    answer+='L'; 
                    lh = v[i]; 
                }
            }                       
        }
    }
    return answer;
}

 

 

코딩테스트 연습 - 키패드 누르기

[1, 3, 4, 5, 8, 2, 1, 4, 5, 9, 5] "right" "LRLLLRLLRRL" [7, 0, 8, 2, 8, 3, 1, 5, 7, 6, 2] "left" "LRLLRRLLLRR" [1, 2, 3, 4, 5, 6, 7, 8, 9, 0] "right" "LLRLLRLLRL"

programmers.co.kr

 

반응형

댓글