[Programmers] 키패드 누르기

Date:

[Programmers] 키패드 누르기

Problem URL : 키패드 누르기

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

string solution(vector<int> numbers, string hand) {
    string answer = "";
    int dx[] = {2, 1, 2, 3, 1, 2, 3, 1, 2, 3};
    int dy[] = {4, 1, 1, 1, 2, 2, 2, 3, 3, 3};
    int lx = 1, ly = 4, rx = 1, ry = 4;
    int ld, rd;
    bool right = false;
    if (hand == "right") {
        right = true;
    }
    for (int i : numbers) {
        if (i == 1 || i == 4 || i == 7) {
            answer.push_back('L');
            lx = dx[i];
            ly = dy[i];
        } else if (i == 3 || i == 6 || i == 9) {
            answer.push_back('R');
            rx = dx[i];
            ry = dy[i];
        }else {
            ld = abs(lx - dx[i]) + abs(ly - dy[i]);
            rd = abs(rx - dx[i]) + abs(ry - dy[i]);
            if (ld == rd) {
                if (right) {
                    answer.push_back('R');
                    rx = dx[i];
                    ry = dy[i];
                } else {
                    answer.push_back('L');
                    lx = dx[i];
                    ly = dy[i];
                }
            } else if (ld > rd) {
                answer.push_back('R');
                rx = dx[i];
                ry = dy[i];
            } else {
                answer.push_back('L');
                lx = dx[i];
                ly = dy[i];
            }
        } 
    }
    return answer;
}

댓글