알고리즘/프로그래머스
[프로그래머스] 키패드 누르기
송민준
2022. 4. 18. 01:12
https://programmers.co.kr/learn/courses/30/lessons/67256?language=java
코딩테스트 연습 - 키패드 누르기
[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
키패드를 기준으로 어느손을 눌러 주어진 번호를 누를 것인가? 문제이다.
1단계라서 쉽다.
기능별로 쪼개봤다.
public class 키패드누르기 {
private static int[][] phone = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9},
{-1, 0, -1}
};
public String solution(int[] numbers, String hand) {
StringBuilder resultBuilder = new StringBuilder();
int[] leftPosition = {3, 0};
int[] rightPosition = {3, 2};
boolean isLeft = hand.equals("left");
for(int number : numbers) {
int[] numberIndex = findNumberIndex(number);
String useHand = findUseHand(numberIndex, leftPosition, rightPosition, isLeft);
if(useHand.equals("L")) {
leftPosition = numberIndex;
} else {
rightPosition = numberIndex;
}
resultBuilder.append(useHand);
}
return resultBuilder.toString();
}
// 사용할 손 찾기
public String findUseHand(int[] numberIndex, int[] leftPosition, int[] rightPosition, boolean isLeft) {
// 우측이면 오른손
if(numberIndex[1] == 2) {
return "R";
} else if(numberIndex[1] == 0) { // 좌측이면 왼손
return "L";
}
// 중간값이면 계산
int leftMoveCount = Math.abs(numberIndex[0] - leftPosition[0]) + Math.abs(numberIndex[1] - leftPosition[1]);
int rightMoveCount = Math.abs(numberIndex[0] - rightPosition[0]) + Math.abs(numberIndex[1] - rightPosition[1]);
if(leftMoveCount > rightMoveCount) {
return "R";
} else if(leftMoveCount < rightMoveCount) {
return "L";
} else {
return (isLeft) ? "L" : "R";
}
}
// 번호 위치 찾기
public int[] findNumberIndex(int number) {
for(int row = 0; row < phone.length; row++) {
for(int col = 0; col < phone[row].length; col++) {
if(phone[row][col] == number) {
return new int[]{row, col};
}
}
}
return null;
}
}
문제를 풀고 다른 사람 코드를 봤으나
나랑 비슷하거나 가독성이 더 별로여서 참고할게 없었다.