1. 문제
A, B 두 사람이 가위바위보를 한다. A가 이기면 A, B가 이기면 B 그리고 비기면 D를 출력한다.
N이 5이면 n회 가위바위보를 실행한다.
입력
첫 번째 줄에 게임 횟수
두 번째 줄에 A가 낼 가위, 바위, 보 정보 n개
세 번째 줄게 B가 낼 가위, 바위, 보 정보 n개
2 - 1. 나의 풀이
총 9가지의 경우의 수가 있다. 이를 일일히 조건문 다는건 코드 낭비라고 생각함.
최대한 줄여보고자 노력했음
1. a <= b 일 경우:
(1) a == b 일 경우 비김
(2) b=3, a=1 일 경우 a가 이김
(3)그 외에는 b의 승
2. b < a 일 경우
(1) a=3, b=1일 경우 b가 이김
(2) 그 외에는 a의 승
이를 n번 반복하면 된다.
2 - 2. 나의 코드
import java.util.Scanner;
public class Main {
public static void solution(int[] a, int[] b, int n) {
for (int i = 0; i < n; i++) {
if(a[i] <= b[i]){
if(a[i]==b[i]) {System.out.println("D"); continue;}
else if(b[i]==3 && a[i]==1) {System.out.println("A"); continue;}
System.out.println("B");
}else{
if(a[i]==3 && b[i]==1) {System.out.println("B"); continue;}
System.out.println("A");
}
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] a = new int[n];
int[] b = new int[n];
for (int i = 0; i < n; i++) {
a[i] = sc.nextInt();
}
for (int i = 0; i < n; i++) {
b[i] = sc.nextInt();
}
solution(a, b, n);
}
}
3 - 1. 강의 풀이
강의에서는 경우의 수를 이렇게 나눴다.
1. a == b 일 경우
2. a가 이기는 경우
(1) a = 1, b = 3
(2) a = 2, b = 1
(3) a = 3, b = 2
3. 그 외는 b의 승리
그리고 강의에서는 solution 반환타입을 String으로 지정한다.
이를 toCharArray()로 char 배열로 바꾼 뒤 향상된 for문을 사용했다.
3 - 2. 강의 코드
import java.util.Scanner;
public class Main {
public static String solution(int n, int[] a, int[] b) {
String answer = "";
for (int i = 0; i < n; i++) {
if(a[i] == b[i]) answer+="D";
else if (a[i]==1 &&b[i]==3) answer += "A";
else if (a[i] == 2 && b[i] == 1) answer += "A";
else if (a[i] == 3 && b[i] == 2) answer += "A";
else answer += "B";
}
return answer;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] a = new int[n];
int[] b = new int[n];
for (int i = 0; i < n; i++) {
a[i] = sc.nextInt();
}
for (int i = 0; i < n; i++) {
b[i] = sc.nextInt();
}
for (char x : solution(n, a, b).toCharArray()) {
System.out.println(x);
}
}
}
4. 얻어갈 점
1. 문자 하나 씩 개행으로 출력할 때 향샹된 for문 사용하는 것도 좋다!
'자바 알고리즘 문제풀이 > Array(1, 2차원 배열)' 카테고리의 다른 글
6. 뒤집은 소수 (0) | 2023.09.10 |
---|---|
5. 소수(에라토스테네스의 체) (0) | 2023.09.02 |
4. 피보나치 수열 (1) | 2023.08.31 |
2. 보이는 학생 (0) | 2023.08.28 |
1. 큰 수 출력하기 (2) | 2023.08.28 |