영수와 민혁이 숫자 야구 게임을 하고 있다.
- 민혁이 3자리 숫자를 질문
- 영수는 스트라이크(숫자+위치 일치)와 볼(숫자만 일치) 개수로 답변
- 모든 질문/답변을 종합하여 가능한 답의 개수를 출력
제한 조건
- 0이 포함되지 않음
- 각 자리 숫자는 중복되지 않음
0 포함, 숫자 중복 있는 경우 제외| 단계 | 설명 |
|---|---|
| 1 | 123~987 범위를 순회하며 후보 생성 |
| 2 | 0이 포함되거나 중복된 숫자는 제외 |
| 3 | 각 후보를 모든 질문과 비교해 조건 일치 여부 확인 |
| 4 | 조건을 모두 만족하면 count 증가 |
| 5 | 최종 count 출력 |

import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int num = sc.nextInt();
int[][] info = new int[num][3];
for (int i = 0; i < num; i++) {
for (int j = 0; j < 3; j++) {
info[i][j] = sc.nextInt();
}
}
int count = 0;
for (int i = 123; i <= 987; i++) {
int n1 = i / 100;
int n2 = (i % 100 ) / 10;
int n3 = (i % 100 ) % 10;
String s1 = Integer.toString(n1);
String s2 = Integer.toString(n2);
String s3 = Integer.toString(n3);
//만약 0이 있거나, 같은 숫자가 있다면 넘기기
if ((n1 == 0 || n2 == 0 || n3 == 0) || (n1 == n2 || n2 == n3 || n1 == n3)) {
continue;
} else {
boolean isPossible = true;
for (int h = 0; h < num; h++) {
int strikeCount = 0;
int ballCount = 0;
if (s1.charAt(0) == Integer.toString(info[h][0]).charAt(0)) strikeCount++;
else if (Integer.toString(info[h][0]).contains(s1)) ballCount++;
if (s2.charAt(0) == Integer.toString(info[h][0]).charAt(1)) strikeCount++;
else if (Integer.toString(info[h][0]).contains(s2)) ballCount++;
if (s3.charAt(0) == Integer.toString(info[h][0]).charAt(2)) strikeCount++;
else if (Integer.toString(info[h][0]).contains(s3)) ballCount++;
if (strikeCount != info[h][1] || ballCount != info[h][2]) {
isPossible = false;
break;
}
}
if (isPossible) count++;
}
}
System.out.println(count);
}
}
strikeCount++ballCount++breakcount++장점
개선 포인트
String 변환 대신 자리 비교를 정수로 직접 처리 가능int n1 = 456 / 100; // 4
int n2 = (456 / 10) % 10; // 5
int n3 = 456 % 10; // 6
int c1 = 456 / 100; // 4
int c2 = (456 / 10) % 10; // 5
int c3 = 456 % 10; // 6
int q1 = 465 / 100; // 4
int q2 = (465 / 10) % 10; // 6
int q3 = 465 % 10; // 5
int strike = 0;
int ball = 0;
// 첫 번째 자리 비교
if (c1 == q1) strike++;
else if (c1 == q2 || c1 == q3) ball++;
// 두 번째 자리 비교
if (c2 == q2) strike++;
else if (c2 == q1 || c2 == q3) ball++;
// 세 번째 자리 비교
if (c3 == q3) strike++;
else if (c3 == q1 || c3 == q2) ball++;