Algorithm Problem Solving/Programmers

[프로그래머스] 코딩테스트 연습 2020 카카오 인턴십 키패드 누르기

코코자장자장 2021. 11. 24. 15:02

 

안녕하세요 오늘은 프로그래머스 1레벨 키패드 누르기를 c++로 풀어 보았습니다.

 

문제 난이도 자체는 정말 낮지만 테이블 만드는데 시간이 10분이나 걸려버렸습니다.. 하핳... 천천히 만들어서 그런가봐요 ㅠㅠ

 

3 by 4 배열로 index 절대값 거리 차이로도 할 수 있었지만 이게 더 빠를거 같아서(만드는데 시간 짧게 걸릴줄알고) 이렇게 만들어 보았습니다!

 


 

 

#include <string>
#include <vector>
#include <cstring>
using namespace std;

                //to from
int distanceTable[12][12] = 
//0 1 2 3 4 5 6 7 8 9 * # 
{{0,0,3,0,0,2,0,0,1,0,0,0},//0to
 {4,0,1,0,0,2,0,0,3,0,0,0},//1to
 {3,0,0,0,0,1,0,0,2,0,0,0},//2to
 {4,0,1,0,0,2,0,0,3,0,0,0},//3to
 {3,0,2,0,0,1,0,0,2,0,0,0},//4to
 {2,0,1,0,0,0,0,0,1,0,0,0},//5to
 {3,0,2,0,0,1,0,0,2,0,0,0},//6to
 {2,0,3,0,0,2,0,0,1,0,0,0},//7to
 {1,0,2,0,0,1,0,0,0,0,0,0},//8to
 {2,0,3,0,0,2,0,0,1,0,0,0},//9to
 {1,0,4,0,0,3,0,0,2,0,0,0},//*to
 {1,0,4,0,0,3,0,0,2,0,0,0}};//#to

string solution(vector<int> numbers, string hand) {
    string answer = "";
    int cnt = numbers.size();
    char LStatus = 10, RStatus = 11;
    
    for(int i = 0; i < cnt; i++) {
        if(numbers[i] == 1 || numbers[i] == 4 || numbers[i] == 7){
            LStatus = numbers[i];
            answer.push_back('L');
        }
        else if(numbers[i] == 3 || numbers[i] == 6 || numbers[i] == 9){
            RStatus = numbers[i];
            answer.push_back('R');
        }
        else {
            if (distanceTable[LStatus][numbers[i]] < distanceTable[RStatus][numbers[i]]){
                LStatus = numbers[i];
                answer.push_back('L');
            }
            else if(distanceTable[LStatus][numbers[i]] > distanceTable[RStatus][numbers[i]]){
                RStatus = numbers[i];
                answer.push_back('R');
            }
            else {
                if(strcmp(hand.c_str(), "right") == 0){
                    RStatus = numbers[i];
                    answer.push_back('R');                  
                }
                else {
                    LStatus = numbers[i];
                    answer.push_back('L');     
                }
            }
        }
    }
    return answer;
}