반응형
👇 문제 URL 👇
프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
2,5,8,0일 경우 오른손, 왼손이 위치한 키패드에서의 거리를 구해야 했기 때문에 좌표를 이용하여 풀었다.
그리고 Stream API에 있는 anyMatch를 이용하여 최소한 한 개의 요소가 주어진 조건에 만족하는지를 체크하였다.
import java.util.Arrays;
class Solution {
public String solution(int[] numbers, String hand) {
String answer = "";
int[] leftHand = {1,4,7};
int[] rightHand = {3,6,9};
int[] leftHandLocation = {3,0};
int[] rightHandLocation = {3,2};
StringBuffer sb = new StringBuffer();
for(int num : numbers){
//1,4,7인 경우
if(Arrays.stream(leftHand).anyMatch( a -> a==num)){
sb.append("L");
leftHandLocation = getIndex(num);
//3,6,9인 경우
}else if(Arrays.stream(rightHand).anyMatch( a -> a==num)){
sb.append("R");
rightHandLocation = getIndex(num);
//2,5,8,0 인 경우
}else{
int[] index = getIndex(num);
int rightResult = Math.abs(index[0] - rightHandLocation[0])+ Math.abs(index[1] - rightHandLocation[1]);
int leftResult = Math.abs(index[0] - leftHandLocation[0])+ Math.abs(index[1] - leftHandLocation[1]);
if(rightResult>leftResult){
sb.append("L");
leftHandLocation = getIndex(num);
}else if(rightResult<leftResult){
sb.append("R");
rightHandLocation = getIndex(num);
}else{
hand = hand.toUpperCase().substring(0,1);
if(hand.equals("R")){
rightHandLocation = getIndex(num);
}else{
leftHandLocation = getIndex(num);
}
sb.append(hand);
}
}
}
answer = sb.toString();
return answer;
}
//좌표 구하기. [0]은 x좌표, [1]은 y좌표
public int[] getIndex(int num){
int[][] pad = {{1, 2, 3}, {4,5,6,}, {7,8,9}, {10,0,11}};
int[] result = new int[2];
for(int i =0 ; i<pad.length; i++){
for(int j=0; j<pad[i].length; j++){
if(pad[i][j] == num){
result[0] = i;
result[1] = j;
}
}
}
return result;
}
}

728x90
반응형
'개발 > 알고리즘' 카테고리의 다른 글
[프로그래머스/JAVA] 체육복 (0) | 2022.07.25 |
---|---|
[프로그래머스/JAVA] 숫자 문자열과 영단어 (0) | 2022.07.24 |
[프로그래머스/JAVA] 신규 아이디 추천 (0) | 2022.07.24 |
[프로그래머스/JAVA] 로또의 최고 순위와 최저 순위 (0) | 2022.07.24 |
[프로그래머스/JAVA] 신고 결과 받기 (1) | 2022.07.24 |
댓글