https://school.programmers.co.kr/learn/courses/30/lessons/67256
키패드를 좌표로 저장하는게 관건이였다.
나는 배열 처럼 생각하고 이를 풀었다. 즉
[4][3]의 배열이라 생각하고 각 다이얼에 해당하는 좌표를 map에다가 넣어주고 풀었다.
import java.util.*;
class Solution {
public String solution(int[] numbers, String hand) {
StringBuilder sb = new StringBuilder();
Map<Integer, Point> map = new HashMap<>();
map.put(0, new Point(3, 1));
Point leftHand = new Point(3, 0);
Point rightHand = new Point(3, 2);
for(int i = 0; i < 3; i++){
for(int j = 0; j < 3; j++){
map.put((3 * i) + (j+1), new Point(i, j));
}
}
for(int number : numbers){
if(number == 1 || number == 4 || number == 7){
leftHand = map.get(number);
sb.append("L");
} else if(number == 3 || number == 6 || number == 9){
rightHand = map.get(number);
sb.append("R");
} else{ // 2, 5, 8, 0
Point p = map.get(number);
int leftDis = Math.abs(leftHand.x - p.x) + Math.abs(leftHand.y - p.y);
int rightDis = Math.abs(rightHand.x - p.x) + Math.abs(rightHand.y - p.y);
if(leftDis < rightDis){
leftHand = p;
sb.append("L");
} else if(leftDis > rightDis){
rightHand = p;
sb.append("R");
} else{
if(hand.equals("left")){
leftHand = p;
sb.append("L");
} else{
rightHand = p;
sb.append("R");
}
}
}
}
return sb.toString();
}
public class Point{
int x;
int y;
public Point(int x, int y){
this.x = x;
this.y = y;
}
}
}