[프로그래머스 Lv1] 키패드 누르기

수민이슈·2023년 4월 25일
0

[C++] 코딩테스트

목록 보기
25/116
post-thumbnail

🖊️ 문제

https://school.programmers.co.kr/learn/courses/30/lessons/67256

🖊️ 풀이

구현만 하면 되는 간단한 코드인데
왜 틀렸냐면 !!
두 점 사이의 거리를 구하는데
피타고라스 방식으로 pow(a.x - b.x, 2) + pow(a.y - b.y, 2) 이렇게 비교하려고 했으나
문제를 잘 읽어보면
상하좌우로만 움직일 수 있다고 했으니
abs(a.x - b.x) + abs(a.y - b.y) 이렇게 구해야 한다.

그걸 제외하면..!!
0을 11로, *과 #을 각각 10, 12로 바꿔주면 쉽게 계산할 수 있고,
숫자 키패드가

이렇게 위치한다고 가정해보면
x축 = n-1을 3으로 나눈 나머지
y축 = n-1을 3으로 나눈 몫
이다.
개쉽죵
그래서 위치를 쉽게 구할 수 있다!

🖊️ 코드

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

using namespace std;

int GetDistance(int a, int b) {
    // return pow(a.x - b.x, 2) + pow(a.y - b.y, 2);
    return abs((a-1)%3 - (b-1)%3) + abs((a-1)/3 - (b-1)/3);
}

string solution(vector<int> numbers, string hand) {
    string answer = "";
    int lh = 10;
    int rh = 12;
    
    for (auto& num : numbers) {
        if (num == 1 || num == 4 || num == 7) {
            answer += 'L';
            lh = num;
        }
        else if (num == 3 || num == 6 || num == 9) {
            answer += 'R';
            rh = num;
        }
        else {
            if (num == 0) num = 11;
            
            int ld = GetDistance(lh, num);
            int rd = GetDistance(rh, num);
            
            if (ld < rd) {
                answer += 'L';
                lh = num;
            }
            else if (ld > rd) {
                answer += 'R';
                rh = num;
            }
            else {
                if (hand == "right") {
                    answer += 'R';
                    rh = num;
                }
                else {
                    answer += 'L';
                    lh = num;
                }
            }
        }
    }
    return answer;
}

0개의 댓글