프로그래머스 - 키패드 누르기

well-life-gm·2021년 11월 14일
0

프로그래머스

목록 보기
48/125

프로그래머스 - 키패드 누르기

키패드를 누를 때, 어느 손가락을 누를지 결과값을 리턴하면 되는 문제이다.
1,4,7은 왼손을 3,6,9는 오른손을 그 외 숫자는 가까운 손으로 누르면 된다.
처음 왼손, 오른손은 *, #에 있다.

쉽게 풀기 위해서 *, #은 10과 12로 매핑하고, 0은 11로 매핑한다.

그리고 모든 숫자에 대해서 -1을 한 뒤 거리를 구한다.
또한 거리를 구할 땐 나누기 연산과 모듈러 연산을 수행해서 행 열을 계산한다.

예를 들어, 2를 누를 때, 이미 왼손은 1을 눌렀었고, 오른손은 6을 눌렀다고 가정하면
(0,1)~(0,0)까지의 거리 : 1
(0,1)~(1,2)까지의 거리 : 2 가 되기 때문에 왼손으로 2를 누르면 된다.

코드는 아래와 같다.

#include <string>
#include <vector>
#include <cmath>

using namespace std;

void get_distance(int num, int left_hand, int right_hand, int &left_dist, int &right_dist)
{
    int row = (int)num / 3;
    int l_row = (int)left_hand / 3;
    int r_row = (int)right_hand / 3;
    int col = num % 3;
    int l_col = left_hand % 3;
    int r_col = right_hand % 3;
    left_dist = abs(row - l_row) + abs(col - l_col);
    right_dist = abs(row - r_row) + abs(col - r_col);
}

string solution(vector<int> numbers, string hand) {
    string answer = "";
    int left_hand = 9;
    int right_hand = 11;
    for(int i=0;i<numbers.size();i++) {
        int num = numbers[i];
        if(num == 0) 
            num = 11;
        num--;
        if(num == 0 || num == 3 || num == 6) {
            answer += "L";
            left_hand = num;
        } else if(num == 2 || num == 5 || num == 8) {
            answer += "R";
            right_hand = num;
        } else {
            int left_dist, right_dist;
            get_distance(num, left_hand, right_hand, left_dist, right_dist);
            if(left_dist < right_dist) {
                answer += "L";
                left_hand = num;
            } else if(left_dist > right_dist) {
                answer += "R";
                right_hand = num;
            } else {
                if(hand == "left") {
                    answer += "L";
                    left_hand = num;
                } else {
                    answer += "R";
                    right_hand = num;
                }
            }
        }
        
    }
    
    return answer;
}
profile
내가 보려고 만든 블로그

0개의 댓글