반응형
문제 링크
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
문제 풀이
간단한 시뮬레이션 문제로 보인다. 다음과 같은 순서로 풀었다.
- 위치를 표현해주는 클래스를 생성한다.
- 각 숫자에 해당하는 위치를 가진 position배열을 생성해준다.
- 각 숫자에 맞게 위치를 배열에 집어넣는다.
- 왼쪽 손의 위치를 가진 변수를 생성한다.
- 오른쪽 손의 위치를 가진 변수를 생성한다.
- 반복문을 통해 키패드를 누를 번호를 가져온다.
- 움직일 손을 케이스를 통해 결정한다.
[케이스]
1) 1,4,7의 경우 -> 왼쪽 손
2) 3,6,9의 경우 -> 오른쪽손
3) 나머지의 경우 거리를 계산과 왼손, 오른손잡이 비교 후 결정
소스 코드
class Pair {
int x;
int y;
public Pair(int x, int y) {
super();
this.x = x;
this.y = y;
}
}
class Solution {
public static String solution(int[] numbers, String hand) {
StringBuffer sb = new StringBuffer();
Pair left = new Pair(3, 0);
Pair right = new Pair(3, 2);
Pair [] position = new Pair[10];
position[0] = new Pair(3, 1);
for(int i=1 ; i< 10; i++) {
position[i] = new Pair((i-1)/3, (i-1)%3);
}
for (int num : numbers) {
Pair pos = position[num];
if(num==1 || num==4 || num==7) {
sb.append("L");
left = pos;
}else if(num==3 || num==6 || num==9) {
sb.append("R");
right = pos;
}else {
int leftDistance = Math.abs(left.x -pos.x) +Math.abs(left.y -pos.y);
int rightDistance = Math.abs(right.x -pos.x) +Math.abs(right.y -pos.y);
if(leftDistance == rightDistance) {
if("left".equals(hand)) {
sb.append("L");
left = pos;
}else {
sb.append("R");
right = pos;
}
}else if(leftDistance< rightDistance){
sb.append("L");
left = pos;
}else {
sb.append("R");
right = pos;
}
}
}
return sb.toString();
}
}
반응형
'Problem Solving' 카테고리의 다른 글
[프로그래머스/Java] 문자열 내 마음대로 정렬하기 (2) | 2020.12.09 |
---|---|
[프로그래머스/Java] 모의고사 (1) | 2020.12.08 |
[SWEA / JAVA] 10966 물놀이를 가자. (3) | 2020.12.03 |
[프로그래머스/JAVA] 삼각 달팽이 (1) | 2020.12.03 |
[프로그래머스/Java] 문자열 내 p와 y의 개수 (1) | 2020.12.02 |