ch. 4 조건문과 반복문
2021. 3. 11. 20:56ㆍJava
728x90
1. 프로그래머스 코딩테스트 연습문제
1.1 키패드 누르기
- 반복문 for, 조건문 if(else if), switch 사용
맨 처음 왼손 엄지손가락은 * 키패드에 오른손 엄지손가락은 # 키패드 위치에서 시작하며, 엄지손가락을 사용하는 규칙은 다음과 같습니다.
- 엄지손가락은 상하좌우 4가지 방향으로만 이동할 수 있으며 키패드 이동 한 칸은 거리로 1에 해당합니다.
- 왼쪽 열의 3개의 숫자 1, 4, 7을 입력할 때는 왼손 엄지손가락을 사용합니다.
- 오른쪽 열의 3개의 숫자 3, 6, 9를 입력할 때는 오른손 엄지손가락을 사용합니다.
- 가운데 열의 4개의 숫자 2, 5, 8, 0을 입력할 때는 두 엄지손가락의 현재 키패드의 위치에서 더 가까운 엄지손가락을 사용합니다.
4-1. 만약 두 엄지손가락의 거리가 같다면, 오른손잡이는 오른손 엄지손가락, 왼손잡이는 왼손 엄지손가락을 사용합니다.
순서대로 누를 번호가 담긴 배열 numbers, 왼손잡이인지 오른손잡이인 지를 나타내는 문자열 hand가 매개변수로 주어질 때, 각 번호를 누른 엄지손가락이 왼손인 지 오른손인 지를 나타내는 연속된 문자열 형태로 return 하도록 solution 함수를 완성해주세요.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
|
class Solution {
public String solution(int[] numbers, String hand) {
String rHand = "right";
String lHand = "left";
String answer = "";
int leftLocation = 10;
int rightLocation = 12;
for (int i : numbers) {
if (i == 1 || i == 4 || i == 7) {
answer += "L";
leftLocation = i;
} else if (i == 3 || i == 6 || i == 9) {
answer += "R";
rightLocation = i;
} else {
int l = distinct(i, leftLocation);
int r = distinct(i, rightLocation);
if (l - r > 0 || (l - r == 0 && hand.equals(rHand))) {
answer += "R";
rightLocation = i;
} else {
answer += "L";
leftLocation = i;
}
}
}
return answer;
}
private int distinct(int i, int handLocation) {
if (i == handLocation)
return 0;
switch (i) {
case 2:
if (handLocation == 1 || handLocation == 3 || handLocation == 5)
return 1;
if (handLocation == 7 || handLocation == 9 || handLocation == 0)
return 3;
if (handLocation == 10 || handLocation == 12)
return 4;
else
return 2;
case 5:
if (handLocation == 2 || handLocation == 4 || handLocation == 6 || handLocation == 8)
return 1;
if (handLocation == 10 || handLocation == 12)
return 3;
else
return 2;
case 8:
if (handLocation == 5 || handLocation == 7 || handLocation == 9 || handLocation == 0)
return 1;
if (handLocation == 1 || handLocation == 3)
return 3;
else
return 2;
case 0:
if (handLocation == 12 || handLocation == 10 || handLocation == 8)
return 1;
if (handLocation == 2 || handLocation == 4 || handLocation == 6)
return 3;
if (handLocation == 1 || handLocation == 3)
return 4;
else
return 2;
}
return 0;
}
}
|
cs |
728x90
'Java' 카테고리의 다른 글
프로그래머스 코딩테스트 연습 level1 크레인 인형뽑기게임 (0) | 2021.04.02 |
---|---|
ch. 5 참조타입 - 배열 타입 (0) | 2021.03.17 |
ch. 5 참조타입 (0) | 2021.03.17 |
Ch.2 변수와 타입 (0) | 2021.03.08 |
Ch.1 java 시작하기 (0) | 2021.03.08 |