[SWExpertAcademy] 1768. [SW Test 샘플문제] 숫자야구게임
풀이
- 0123 ~ 9876까지 정답이 될 수 있는 경우의 길이만큼의 배열을 생성
- 0123부터 9876까지 정답 가능성이 있는 수를 제출
- 제출한 수의 결과(strike와 ball의 수)를 통해 가지치기
- strike가 4가 될 때까지 2 ~ 3 반복
코드
public class UserSolution {
public final static int N = 4;
static boolean possible[];
static int number[];
static int index;
void init() {
index = 0;
number = new int[5040];
possible = new boolean[9877];
for(int i=123;i<=9876;i++) {
int num1 = i / 1000;
int num2 = i % 1000 / 100;
int num3 = i % 100 / 10;
int num4 = i % 10;
if(num1 != num2 && num1 != num3 && num1 != num4 && num2 != num3 && num2 != num4 && num3 != num4) {
number[index++] = i;
possible[i] = true;
}
}
}
public void doUserImplementation(int guess[]) {
init();
int answer=0,ball=0,strike=0, target = 0, res = 0,ballCount[];
while(true) {
for(int i=0;i<index;i++) {
if(possible[number[i]]) {
answer = number[i];
guess[0] = answer / 1000;
guess[1] = answer % 1000 / 100;
guess[2] = answer % 100 / 10;
guess[3] = answer % 10;
break;
}
}
Solution.Result result = Solution.query(guess);
if(result.strike == 4)break;
else possible[answer] = false;
for(int i=0;i<index;i++) {
if(possible[number[i]]) {
res = answer;
target = number[i];
ball = 0;
strike = 0;
ballCount = new int[10];
for(int j=0;j<4;j++) {
if(res%10 == target%10)strike++;
else {
ballCount[res%10]++;
ballCount[target%10]++;
}
res/=10;
target/=10;
}
for(int j=0;j<10;j++) {
if(ballCount[j]==2)ball++;
}
if(strike != result.strike || ball != result.ball) possible[number[i]] = false;
}
}
}
}
}