发布网友 发布时间:2022-04-23 13:54
共1个回答
热心网友 时间:2023-10-16 01:53
#include <iostream>
#include <time.h>
#define SIZE 4
#define MAX 3
char c[MAX] = { 'R', 'G', 'B' };
using namespace std;
class Item
{
public:
int a[SIZE];
void CreateByArray(int* ar, int size )
{
if( size < SIZE )
return;
int i;
for( i=0; i<SIZE; i++ )
a[i] = ar[i];
}
void CreateByRand()
{
int i;
cout<<"随机生成"<<endl;
for( i=0; i<SIZE; i++ )
{
a[i] = rand()%MAX;
cout<<c[ a[i] ];
}
cout<<endl;
}
void CreateByInput()
{
int i;
char str[100];
int count = 0;
cin>>str;
int size = sizeof(str);
cout<<"输入获取"<<endl;;
for( i=0; i<size && count<size; i++ )
{
char ch = str[i];
switch(ch)
{
case 'R':
a[count] = 0;
cout<<c[ a[count] ];
count++;
break;
case 'G':
a[count] = 1;
cout<<c[ a[count] ];
count++;
break;
case 'B':
a[count] = 2;
cout<<c[ a[count] ];
count++;
break;
case '\n':
count = 0;
break;
default:
break;
}
}
cout<<endl;
}
int check1( Item& item )
{
int i,j;
int ret = 0;
for( i=0; i<MAX; i++ )
{
int c1=0, c2=0;
for( j=0; j<SIZE; j++ )
{
if( a[j] == i )
c1++;
if( item.a[j] == i )
c2++;
}
ret += c1<c2?c1:c2;
}
return ret;
}
int check2( Item& item )
{
int ret = 0;
int i;
for( i=0; i<SIZE; i++ )
{
if( a[i] == item.a[i] )
ret++;
}
return ret;
}
void check(Item& item)
{
cout<<"猜测结果"<<endl;;
cout<<check1(item);
cout<<" ";
cout<<check2(item);
cout<<endl<<endl;
}
};
int main()
{
srand( time(0) );
while( true )
{
Item item, item1;
item.CreateByRand();
item1.CreateByInput();
item1.check(item);
}
}
参考资料:随便写的,程序运行还是没有问题的.但是封装的不是很好,自己优化下吧.