Hayden's Archive
[알고리즘] 프로그래머스 : 키패드 누르기 본문
알고리즘 문제 출처 : programmers.co.kr/learn/courses/30/lessons/67256
내가 작성한 코드
public class Solution {
private String answer = "";
private String leftNum = "*";
private String rightNum = "#";
public String solution(int[] numbers, String hand) {
String[][] line = {{"1", "4", "7", "*"},
{"2", "5", "8", "0"},
{"3", "6", "9", "#"}};
for(int i=0; i<numbers.length; i++) {
String thisNum = numbers[i] + "";
if(thisNum.equals("1") || thisNum.equals("4") || thisNum.equals("7")) {
setValue("L", thisNum);
}else if(thisNum.equals("3") || thisNum.equals("6") || thisNum.equals("9")) {
setValue("R", thisNum);
}else {
int[] thisIdx = new int[2];
int[] leftIdx= new int[2];
int[] rightIdx = new int[2];
for(int j=0; j<line.length; j++) {
for(int k=0; k<line[j].length; k++) {
if(line[j][k].equals(thisNum)) {
thisIdx[0] = j;
thisIdx[1] = k;
}
if(line[j][k].equals(leftNum)) {
leftIdx[0] = j;
leftIdx[1] = k;
}
if(line[j][k].equals(rightNum)) {
rightIdx[0] = j;
rightIdx[1] = k;
}
}
}
int distanceL0 = Math.abs(thisIdx[0]-leftIdx[0]);
int distanceL1 = Math.abs(thisIdx[1]-leftIdx[1]);
int distanceR0 = Math.abs(thisIdx[0]-rightIdx[0]);
int distanceR1 = Math.abs(thisIdx[1]-rightIdx[1]);
if((distanceL0+distanceL1) < (distanceR0+distanceR1)) {
setValue("L", thisNum);
}else if((distanceL0+distanceL1) > (distanceR0+distanceR1)) {
setValue("R", thisNum);
}else {
if(hand.equals("left")) {
setValue("L", thisNum);
}else {
setValue("R", thisNum);
}
}
}
}
return this.answer;
}
public void setValue(String direction, String num) {
this.answer += direction;
if(direction.equals("L")) {
this.leftNum = num;
}else {
this.rightNum = num;
}
}
}