[숫자 야구]
* 로직
- 1~9까지 숫자 중 3가지 수를 뽑는 모든 경우를 구한다(순열)
- 숫자가 만들어질 때마다 baseball 질문 개수만큼 비교를 진행한다
- 만약 질문의 결과와 일치하지 않는다면 false
- 모두 다 일치한다면 true
- 모두 다 일치하게되면 답을 카운팅한다
// 숫자야구
public class Problem_NumberBaseball {
static boolean[] checked;
static int[] arr;
static int N;
static int R;
static int result;
public static void main(String[] args) {
int[][] baseball = {
{123, 1, 1}, {356, 1, 0}, {327, 2, 0}, {489, 0, 1}
};
int answer = solution(baseball);
System.out.println(answer);
}
public static int solution(int[][] baseball) {
int answer = 0;
N = 9;
checked = new boolean[N+1];
// 1~9까지의 숫자 중 3개를 뽑는 경우(순열)
int count=0;
R = 3;
arr = new int[R];
result = 0;
doProcess(count, baseball);
return answer = result;
}
private static void doProcess(int count, int[][] baseball) {
if(count == R) {
StringBuilder sb = new StringBuilder();
for(int tmp : arr) {
sb.append(tmp);
}
// baseball과 비교
if(possible(sb, baseball)) result++;
return;
}
for(int i=1; i<=N; ++i){
if(!checked[i]){
checked[i] = true;
arr[count] = i;
doProcess(count+1, baseball);
checked[i] = false;
}
}
}
private static boolean possible(StringBuilder sb, int[][] baseball) {
for(int[] input : baseball) {
String num = Integer.toString(input[0]);
int strike = input[1];
int ball = input[2];
// baseball의 입력된 숫자 한 글자씩을 기준으로 순열로 만들어진 수의 한 글자씩 비교
for(int s=0; s<num.length(); ++s) {
String word = num.substring(s, s+1);
for(int i=0; i<sb.length(); ++i) {
// 우선 값이 같다면
if(sb.substring(i, i+1).equals(word)) {
//위치도 같다면 -> strike
if(i == s) strike--;
//위치가 다르다면 -> ball
else ball--;
}
}
}
if(strike != 0 || ball != 0) return false;
}
return true;
}
}
'Algorithm > Problem_프로그래머스' 카테고리의 다른 글
알고리즘(단체사진 찍기, 올바른 괄호, 다음 큰 숫자) (0) | 2020.04.21 |
---|---|
알고리즘(라면 공장, 가장 큰 정사각형 찾기) (0) | 2020.04.20 |
알고리즘(위장) (0) | 2020.04.15 |
알고리즘(소수 찾기, 더 맵게, H-Index) (0) | 2020.04.14 |
알고리즘(소수 만들기, 점프와 순간이동, 영어 끝말잇기) (0) | 2020.04.06 |