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

 

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

[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

 

#include <string>
#include <vector>

using namespace std;

string solution(vector<int> numbers, string hand) {
	string answer = "";
	int right_location = 10;
	int left_location = 12;

	for (int i = 0; i < numbers.size(); i++)
	{
		int temp = numbers[i];
		if (temp == 0) { temp = 11; }	// 0일때의 위치

		if (temp % 3 == 1)
		{
			left_location = temp;
			answer.append("L");
		}
		else if (temp % 3 == 0)
		{
			right_location = temp;
			answer.append("R");
		}
		else
		{
			// 행 거리 차이
			int right_dis = abs((right_location - 1) / 3 - temp / 3);
			int left_dis = abs((left_location - 1) / 3 - temp / 3);

			// 열 거리 차이
			right_dis += abs((right_location - 1) % 3 - (temp - 1) % 3);
			left_dis += abs((left_location - 1) % 3 - (temp - 1) % 3);
			
			if (right_dis < left_dis)
			{
				right_location = temp;
				answer.append("R");
			}
			else if (right_dis > left_dis)	// left 거리가 더 짭을때
			{
				left_location = temp;
				answer.append("L");
			}
			else
			{
				if (hand == "right") { right_location = temp; answer.append("R"); }
				else { left_location = temp; answer.append("L"); }
			}
		}
	}

	return answer;
}

int main() {
	vector<int> ex = { 7, 0, 8, 2, 8, 3, 1, 5, 7, 6, 2 };
	solution(ex, "left");
}

'알고리즘 > Coding Test' 카테고리의 다른 글

음양 더하기 C++  (0) 2022.05.19
없는 숫자 더하기 C++  (0) 2022.05.19
숫자 문자열과 영단어 C++  (0) 2022.05.18
신규 아이디 추천 C++  (0) 2022.05.18
신고 결과 받기 C++  (0) 2022.05.17

+ Recent posts