👨💻 Coding Test/Programers
[Programmers/Java/Lv.1/시뮬레이션] 44.키패드 누르기
Developer Quarterly
2025. 5. 26. 17:09
문제 설명
스마트폰 전화 키패드의 각 칸에 다음과 같이 숫자들이 적혀 있습니다.
이 전화 키패드에서 왼손과 오른손의 엄지손가락만을 이용해서 숫자만을 입력하려고 합니다.
맨 처음 왼손 엄지손가락은 * 키패드에 오른손 엄지손가락은 # 키패드 위치에서 시작하며, 엄지손가락을 사용하는 규칙은 다음과 같습니다.
- 엄지손가락은 상하좌우 4가지 방향으로만 이동할 수 있으며 키패드 이동 한 칸은 거리로 1에 해당합니다.
- 왼쪽 열의 3개의 숫자 1, 4, 7을 입력할 때는 왼손 엄지손가락을 사용합니다.
- 오른쪽 열의 3개의 숫자 3, 6, 9를 입력할 때는 오른손 엄지손가락을 사용합니다.
- 가운데 열의 4개의 숫자 2, 5, 8, 0을 입력할 때는 두 엄지손가락의 현재 키패드의 위치에서 더 가까운 엄지손가락을 사용합니다.
-만약 두 엄지손가락의 거리가 같다면, 오른손잡이는 오른손 엄지손가락, 왼손잡이는 왼손 엄지손가락을 사용합니다.
순서대로 누를 번호가 담긴 배열 numbers, 왼손잡이인지 오른손잡이인 지를 나타내는 문자열 hand가 매개변수로 주어질 때, 각 번호를 누른 엄지손가락이 왼손인 지 오른손인 지를 나타내는 연속된 문자열 형태로 return 하도록 solution 함수를 완성해주세요.
제한사항
- numbers 배열의 크기는 1 이상 1,000 이하입니다.
- numbers 배열 원소의 값은 0 이상 9 이하인 정수입니다.
- hand는 "left" 또는 "right" 입니다.
-"left"는 왼손잡이, "right"는 오른손잡이를 의미합니다. - 왼손 엄지손가락을 사용한 경우는 L, 오른손 엄지손가락을 사용한 경우는 R을 순서대로 이어붙여 문자열 형태로 return 해주세요.
입출력 예
numbers | hand | result |
[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" |
나의 풀이
import java.util.*;
class Solution {
public String solution(int[] numbers, String hand) {
String answer = "";
String leftLocation = "*";
String rightLocation = "#";
for (int i = 0; i < numbers.length; i++) {
if (numbers[i] == 1 || numbers[i] == 4 || numbers[i] == 7) {
leftLocation = String.valueOf(numbers[i]);
answer += "L";
} else if (numbers[i] == 3 || numbers[i] == 6 || numbers[i] == 9) {
rightLocation = String.valueOf(numbers[i]);
answer += "R";
} else { // numbers[i] == 2, 5, 8, 0
int leftDistance = 0;
int rightDistance = 0;
if (numbers[i] == 2) {
if (leftLocation.equals("1")) leftDistance = 1;
else if (leftLocation.equals("4")) leftDistance = 2;
else if (leftLocation.equals("7")) leftDistance = 3;
else if (leftLocation.equals("*")) leftDistance = 4;
else if (leftLocation.equals("2")) leftDistance = 0;
else if (leftLocation.equals("5")) leftDistance = 1;
else if (leftLocation.equals("8")) leftDistance = 2;
else if (leftLocation.equals("0")) leftDistance = 3;
if (rightLocation.equals("3")) rightDistance = 1;
else if (rightLocation.equals("6")) rightDistance = 2;
else if (rightLocation.equals("9")) rightDistance = 3;
else if (rightLocation.equals("#")) rightDistance = 4;
else if (rightLocation.equals("2")) rightDistance = 0;
else if (rightLocation.equals("5")) rightDistance = 1;
else if (rightLocation.equals("8")) rightDistance = 2;
else if (rightLocation.equals("0")) rightDistance = 3;
} else if (numbers[i] == 5) {
if (leftLocation.equals("1")) leftDistance = 2;
else if (leftLocation.equals("4")) leftDistance = 1;
else if (leftLocation.equals("7")) leftDistance = 2;
else if (leftLocation.equals("*")) leftDistance = 3;
else if (leftLocation.equals("2")) leftDistance = 1;
else if (leftLocation.equals("5")) leftDistance = 0;
else if (leftLocation.equals("8")) leftDistance = 1;
else if (leftLocation.equals("0")) leftDistance = 2;
if (rightLocation.equals("3")) rightDistance = 2;
else if (rightLocation.equals("6")) rightDistance = 1;
else if (rightLocation.equals("9")) rightDistance = 2;
else if (rightLocation.equals("#")) rightDistance = 3;
else if (rightLocation.equals("2")) rightDistance = 1;
else if (rightLocation.equals("5")) rightDistance = 0;
else if (rightLocation.equals("8")) rightDistance = 1;
else if (rightLocation.equals("0")) rightDistance = 2;
} else if (numbers[i] == 8) {
if (leftLocation.equals("1")) leftDistance = 3;
else if (leftLocation.equals("4")) leftDistance = 2;
else if (leftLocation.equals("7")) leftDistance = 1;
else if (leftLocation.equals("*")) leftDistance = 2;
else if (leftLocation.equals("2")) leftDistance = 2;
else if (leftLocation.equals("5")) leftDistance = 1;
else if (leftLocation.equals("8")) leftDistance = 0;
else if (leftLocation.equals("0")) leftDistance = 1;
if (rightLocation.equals("3")) rightDistance = 3;
else if (rightLocation.equals("6")) rightDistance = 2;
else if (rightLocation.equals("9")) rightDistance = 1;
else if (rightLocation.equals("#")) rightDistance = 2;
else if (rightLocation.equals("2")) rightDistance = 2;
else if (rightLocation.equals("5")) rightDistance = 1;
else if (rightLocation.equals("8")) rightDistance = 0;
else if (rightLocation.equals("0")) rightDistance = 1;
} else if (numbers[i] == 0) {
if (leftLocation.equals("1")) leftDistance = 4;
else if (leftLocation.equals("4")) leftDistance = 3;
else if (leftLocation.equals("7")) leftDistance = 2;
else if (leftLocation.equals("*")) leftDistance = 1;
else if (leftLocation.equals("2")) leftDistance = 3;
else if (leftLocation.equals("5")) leftDistance = 2;
else if (leftLocation.equals("8")) leftDistance = 1;
else if (leftLocation.equals("0")) leftDistance = 0;
if (rightLocation.equals("3")) rightDistance = 4;
else if (rightLocation.equals("6")) rightDistance = 3;
else if (rightLocation.equals("9")) rightDistance = 2;
else if (rightLocation.equals("#")) rightDistance = 1;
else if (rightLocation.equals("2")) rightDistance = 3;
else if (rightLocation.equals("5")) rightDistance = 2;
else if (rightLocation.equals("8")) rightDistance = 1;
else if (rightLocation.equals("0")) rightDistance = 0;
}
if (leftDistance > rightDistance) {
rightLocation = String.valueOf(numbers[i]);
answer += "R";
} else if (leftDistance < rightDistance) {
leftLocation = String.valueOf(numbers[i]);
answer += "L";
} else {
if (hand.equals("right")) {
rightLocation = String.valueOf(numbers[i]);
answer += "R";
} else if (hand.equals("left")) {
leftLocation = String.valueOf(numbers[i]);
answer += "L";
}
}
}
}
return answer;
}
}
위의 코드는 너무 비효율적이고 하드코딩 방식이라서 리팩토링이 꼭 필요하다.
GPT 리팩토링 코드
import java.util.*;
class Solution {
// 키패드 위치를 나타내는 좌표 맵
private static final Map<Integer, int[]> keypad = new HashMap<>();
static {
keypad.put(1, new int[]{0, 0}); keypad.put(2, new int[]{0, 1}); keypad.put(3, new int[]{0, 2});
keypad.put(4, new int[]{1, 0}); keypad.put(5, new int[]{1, 1}); keypad.put(6, new int[]{1, 2});
keypad.put(7, new int[]{2, 0}); keypad.put(8, new int[]{2, 1}); keypad.put(9, new int[]{2, 2});
keypad.put(0, new int[]{3, 1}); keypad.put(-1, new int[]{3, 0}); // * → -1
keypad.put(-2, new int[]{3, 2}); // # → -2
}
public String solution(int[] numbers, String hand) {
StringBuilder answer = new StringBuilder();
int leftPos = -1; // * 위치
int rightPos = -2; // # 위치
for (int number : numbers) {
if (number == 1 || number == 4 || number == 7) {
answer.append("L");
leftPos = number;
} else if (number == 3 || number == 6 || number == 9) {
answer.append("R");
rightPos = number;
} else { // 가운데 열
int leftDist = getDistance(leftPos, number);
int rightDist = getDistance(rightPos, number);
if (leftDist < rightDist) {
answer.append("L");
leftPos = number;
} else if (rightDist < leftDist) {
answer.append("R");
rightPos = number;
} else {
if (hand.equals("right")) {
answer.append("R");
rightPos = number;
} else {
answer.append("L");
leftPos = number;
}
}
}
}
return answer.toString();
}
// 두 키 위치 간의 거리 계산
private int getDistance(int from, int to) {
int[] fromPos = keypad.get(from);
int[] toPos = keypad.get(to);
return Math.abs(fromPos[0] - toPos[0]) + Math.abs(fromPos[1] - toPos[1]);
}
}
- keypad는 Solution 클래스 내부에서만 사용되므로 외부 클래스가 실수로 접근하거나 수정하지 못하게 정보 은닉을 위해 private
- keypad는 모든 객체에서 공통으로 사용하는 불변 좌표 맵이므로, 인스턴스마다 새로 만들 필요가 없어서 static
- keypad는 절대 바뀌지 않는 상수 데이터(좌표 정보) 이므로, 한 번 초기화한 뒤 변경되지 않도록 final
다른 풀이
class Solution {
// 0부터 9까지 좌표 {y,x}
int[][] numpadPos = {
{3,1}, //0
{0,0}, //1
{0,1}, //2
{0,2}, //3
{1,0}, //4
{1,1}, //5
{1,2}, //6
{2,0}, //7
{2,1}, //8
{2,2} //9
};
//초기 위치
int[] leftPos = {3,0};
int[] rightPos = {3,2};
String hand;
public String solution(int[] numbers, String hand) {
this.hand = (hand.equals("right")) ? "R" : "L";
String answer = "";
for (int num : numbers) {
String Umji = pushNumber(num);
answer += Umji;
if(Umji.equals("L")) {leftPos = numpadPos[num]; continue;}
if(Umji.equals("R")) {rightPos = numpadPos[num]; continue;}
}
return answer;
}
//num버튼을 누를 때 어디 손을 사용하는가
private String pushNumber(int num) {
if(num==1 || num==4 || num==7) return "L";
if(num==3 || num==6 || num==9) return "R";
// 2,5,8,0 일때 어디 손가락이 가까운가
if(getDist(leftPos, num) > getDist(rightPos, num)) return "R";
if(getDist(leftPos, num) < getDist(rightPos, num)) return "L";
//같으면 손잡이
return this.hand;
}
//해당 위치와 번호 위치의 거리
private int getDist(int[] pos, int num) {
return Math.abs(pos[0]-numpadPos[num][0]) + Math.abs(pos[1]-numpadPos[num][1]);
}
}