
1. 123, 124, 125, .... 129, 132, 134, ... 986, 987 까지의 array list를 만든다.
2. 질문들을 입력 받아서 2차원 배열로 저장한다.
3. 1.에서 만든 list의 각 숫자를 질문 숫자와 비교해 strike와 ball이 몇 개 있는지 확인한다.
4. strike와 ball이 다르면 list에서 지운다.
5. 3. 4.를 반복하고 남은 list의 숫자 개수(사이즈)를 출력한다.
쉽게 풀어서 얘기하면, 질문이 123 1 1 일때, arrayList에 있는 123과 비교한다. 1, 2, 3 모두 숫자와 위치가 같은 스트라이크이므로 strike=3, 이고 strike=1, ball=1인 조건과 맞지 않으니 arrayList에서 지운다. 또 다른 arrayList에 있는 325와 비교해보면.. 3은 ball=1, 5는 아무것도 아님, 2는 strike=1 이므로 조건 strike=1, ball=1과 같으므로 arrayList에서 지우지 않는다.
방법을 떠올리고 이해하는데 오랜 시간이 걸렸고.. 코드도 뭔가 난잡하다.. 주석에도 설명 추가했어요.
아래는 전체 코드이다.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.StringTokenizer;
public class BOJ2503 {
// 123부터 987까지 돌면서 해당 숫자가 각각 질문들에 걸러지는 숫자인지 확인하기
// ex) 질문 123 1 1, 확인 할 list의 숫자 123 -> 123은 3스트라이크 -> 삭제
// 124 -> 12 2스트라이크 -> 삭제
// 136 -> 1 1스트라이크 1볼 -> 유지
// 987 -> 0스트라이크 0볼 -> 삭제
// 물론 한 list숫자에 대해 모든 질문들을 확인함.
// 그러나 어떤 질문의 조건에 안 맞으면 다른 질문을 확인 할 필요가 없음 -> 삭제하고 break하기
public static void checkQuestions(Array
List<String> candidates, int N, int[][] questions){
int i, j, strike, ball;
String candi;
Iterator<String> iterator = candidates.iterator();
while(iterator.hasNext()){
candi = iterator.next();
for(i=0;i<N;i++) {
strike = 0;
ball = 0;
for(j=0;j<3;j++){
//strike와 ball 계산
if(candi.charAt(j) == (questions[i][0]+"").charAt(j))
strike++;
else if(candi.contains((questions[i][0]+"").charAt(j)+"")){
ball++;
}
}
// 후보 숫자에 대해 스트라이크와 볼을 계산했을때 틀린 경우
if(strike != questions[i][1] || ball != questions[i][2]) {
iterator.remove();
break;
}
}
}
}
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int N, i;
String str;
ArrayList<String> candidates = new ArrayList<>();
StringTokenizer st;
//후보 숫자 list 초기화
for(i=123;i<988;i++){
str = String.valueOf(i);
if(!str.contains("0")&&(str.charAt(0) != str.charAt(1))
&&(str.charAt(0) != str.charAt(2))&&(str.charAt(1) != str.charAt(2)))
candidates.add(str);
}
N = Integer.parseInt(br.readLine());
int[][] questions = new int[N][3];
// 질문 입력 받기
for(i=0;i<N;i++){
st = new StringTokenizer(br.readLine());
questions[i][0] = Integer.parseInt(st.nextToken()); // 숫자
questions[i][1] = Integer.parseInt(st.nextToken()); // strike 개수
questions[i][2] = Integer.parseInt(st.nextToken()); // ball 개수
}
checkQuestions(candidates, N, questions);
System.out.println(candidates.size());
}
}
'코딩가딩가' 카테고리의 다른 글
| [JAVA]BOJ 15961, 회전 초밥 (0) | 2024.08.18 |
|---|---|
| [JAVA]BOJ 7795, 먹을 것인가 먹힐 것인가 (0) | 2024.08.17 |
| [JAVA]BOJ 1475, 방 번호 (0) | 2024.08.09 |
| [JAVA]BOJ 1406, 에디터 (0) | 2024.08.09 |
| [JAVA]BOJ 1158, 요제푸스 문제 (0) | 2024.08.08 |