实现一个经典"猜数字"游戏。 给定答案序列和用户猜的序列,统计有多少数字位置正确
(A),有多少数字在两个序列都出现过但位置不对(B)。
输入包含多组数据。 每组输入第一行为序列长度n,第二行是答案序列,接下来是若干
猜测序列。 猜测序列全0时该组数据结束。 n=0时输入结束。
样例输入:
4 1
3 5 5
1 1 2 3
4 3 3 5
6 5 5 1
6 1 3 5
1 3 5 5
0 0 0 0
10
1 2 2 2 4 5 6 6 6 9
1 2 3 4 5 6 7 8 9 1
1 1 2 2 3 3 4 4 5 5
1 2 1 3 1 5 1 6 1 9
1 2 2 5 5 5 6 6 6 7
0 0 0 0 0 0 0 0 0 0
0 样
例输出:
Game 1:
(1,1)
(2,0)
(1,2)
(1,2)
(4,0)
Game 2:
(2,4)
(3,2)
(5,0)
(7,0)
A表示在相同位置数值相同数的个数,其较容易算出来,只要比较A[i]与B[i]即可得到A的数值
用两层for循环,可比较A[i]与B[i]中数字相同的个数,将其求和,最后减去A的大小即可得到B。
#include <iostream>
#include <cstdio>
#define maxn 1010
using namespace std;
int main()
{
int n,a[maxn],b[maxn],count = 0;
while(scanf("%d",&n)!=EOF&&n)
{
cout << "Game" << ++count << endl;
for(int i = 0; i < n;i++)
{
cin >> a[i];
}
while(1)
{
int A = 0,B = 0;
for(int i = 0;i < n;i++)
{
cin >> b[i];
if(a[i] == b[i])
{
A++;
}
}
if(b[0] == 0)
{
break;
}
for(int d = 1;d <= 9;d++)
{
int c1 = 0,c2 = 0;
for(int i = 0;i < n;i++)
{
if(a[i] == d)
{
c1++;
}
if(b[i] == d)
{
c2++;
}
}
if(c1 > c2)
{
B += c2;
}
else
{
B += c1;
}
}
printf("(%d,%d)\n",A,B-A);
}
}
return 0;
}
本文介绍了一个经典的猜数字游戏实现方案,通过对比用户猜测的数字序列与答案序列来判断位置正确的数字数量(A)以及数字出现过但位置不正确的数量(B)。使用C++编程语言,并通过双重循环进行比较。
1765

被折叠的 条评论
为什么被折叠?



