■ 数当てゲーム(平成14年午後2問1)
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
/* 平成14年午後2 */
#define N 5040
#define M 255
int log[M], guess[M][10], nums[N], index;
int set_answer()
{
int tab[10], n, i, a;
for (i = 0; i < 10; i++) tab[i] = 0;
n = 0;
for (i = 1; i <= 4; i++) {
do {
a = rand() % 10;
} while (tab[a] != 0);
tab[a] = 1;
n = n * 10 + a;
}
return n;
}
void make_pos(int y, int pos[])
{
int i, m;
for (i = 0; i < 10; i++)
pos[i] = 0;
for (i = 1; i <= 4; i++) {
m = y % 10;
y /= 10;
pos[m] = i;
}
}
int sim(int x, int pos[])
{
int hit, miss, i, p;
hit = 0;
miss = 0;
for (i = 1; i <= 4; i++) {
p = x % 10;
x /= 10;
if (pos[p] != 0) {
if (pos[p] == i) hit++;
else miss++;
}
}
return hit * 10 + miss;
}
int make_guess(int k)
{
int j;
index++;
for (;;) {
j = 0;
while (j < k-1 && sim(nums[index], guess[j]) == log[j])
j++;
if (j < k-1) {
index++;
if (index >= N) index = 0;
} else {
return nums[index];
}
}
return -1;
}
void play()
{
int ans, pos_a[10], i, r, g, hit, miss, guess_person;
ans = set_answer();
make_pos(ans, pos_a);
index = -1;
i = 1;
for (;;) {
rewind(stdin);
scanf("%d", &guess_person);
r = sim(guess_person, pos_a);
printf("%d %d\n", r / 10, r % 10);
g = make_guess(i);
printf("%04d\n", g);
rewind(stdin);
scanf("%d %d", &hit, &miss);
if (hit == 4 || r == 40)
break;
log[i-1] = 10 * hit + miss;
make_pos(g, guess[i-1]);
i++;
}
if (hit != 4)
printf("あなたの勝ちです\n");
else if (r != 40)
printf("私の勝ちです\n");
else
printf("引き分けです\n");
}
void init()
{
int i, j, k, m, p = 0, n[3], t, a, b;
for (i = 0; i <= 9; i++) {
n[0] = i;
for (j = 0; j <= 9; j++) {
if (n[0] != j) {
n[1] = j;
for (k = 0; k <= 9; k++) {
if (n[0] != k && n[1] != k) {
n[2] = k;
for (m = 0; m <= 9; m++) {
if (n[0] != m && n[1] != m && n[2] != m) {
nums[p++] = n[0] * 1000 + n[1] * 100 + n[2] * 10 + m;
}
}
}
}
}
}
}
while (j-- > 0) {
a = rand() % N;
b = rand() % N;
t = nums[a];
nums[a] = nums[b];
nums[b] = t;
}
}
int main()
{
char r;
srand(time(NULL));
init();
for (;;) {
play();
printf("ゲームを続けますか? Y/N");
rewind(stdin);
scanf("%c", &r);
if (r == 'N')
return 0;
}
return 0;
}