一日午晌,顿觉百无聊赖,阵阵哈切之余,竟忆起儿时游玩之小游戏,名曰“猜数字”,此物规则甚是简单,游玩之时仅需猜测一四位数字,接着便可得到相应之正误结果,然后依此继续猜测,如此周而复始,直至猜测功成。
如诸位看官依然不甚了了亦无甚大碍,容我在此以一简单示例剖析之:
譬有一数字1234,游玩者之目的即将其猜出,游戏伊始,游玩之人自不知其所需猜测之数字为何,故其可能胡诌一数字,譬如4253,此猜测数字较之原数字而言,大抵有以下之特点,第一便是数字2,其出现于原数字之中,亦出现于猜测之数之中,并且其所在位置亦相同,皆在百位,故此数可谓之精准匹配,称其为A类型数字;与之相比,数字3虽亦出现于原数字及猜测数字之中,然其位置并不相同,一个处十位,一个处个位,此类数字可谓之次准匹配,称其为B类型数字,故猜测者报出4253之猜测时,其会得到1A1B之反馈,意为猜测数字之中共有一个A类型之数字、一个B类型之数字,猜测之人依此结果继续猜测,直至猜出,一般而言,猜测次数最少之人获胜,有时亦可纳入时间限制之考量。
现时思量一番,与其无聊,不如编写个“猜数字”以期自娱自乐,以免大好韶华匆匆而逝,老大来追悔莫及,既然如此,何不马上动手,图形界面?鼠标跟踪?此等花哨之事大可不必,黑白一个单调控制台,足矣足矣 :)
在此便列出全部之实现代码,数来也不过区区一百来行,如果看官有意,大可完整复制黏贴并编译之 :) ( 本人所用编译器为MinGW(gcc),故并不保证在VC中亦可顺利通过,见谅见谅 )
代码语言:javascript复制#include <iostream>
using std::ostream;
using std::endl;
using std::cout;
using std::cin;
const int NUMBERS_COUNT = 10;//0~9
const int NUMBERS_GUESS = 4;//guess number consist of 4 number
int g_count[NUMBERS_COUNT];//store the counts of numbers (0~9)
int g_buffer[NUMBERS_COUNT][NUMBERS_GUESS];//store the value and number
//init g_count and g_buffer array
void Init()
{
for( int i = 0; i < NUMBERS_COUNT; i )
{
g_count[i] = 0;
for( int j = 0; j < NUMBERS_GUESS; j )
{
g_buffer[i][j] = 0;
}
}
}
struct GuessResult
{
int ACount;//the position and value are both right
int BCount;//just the value is right
GuessResult():ACount(0),BCount(0) {};
friend ostream& operator << ( ostream& o, const GuessResult& gr );
};
ostream& operator << ( ostream& o, const GuessResult& gr )
{
cout<<gr.ACount<<" A "<<gr.BCount<<" B ";
}
GuessResult Evaluate( char originNumber[NUMBERS_GUESS 1], char guessNumber[NUMBERS_GUESS 1] )
{
Init();
//get the information of the originNumber
for( int i = 0; i < NUMBERS_GUESS; i )
{
g_count[ originNumber[i]-'0' ];
g_buffer[originNumber[i]-'0'][i] = 1;
}
GuessResult gr;
for( int i = 0; i < NUMBERS_GUESS; i )
{
if( g_buffer[ guessNumber[i]-'0' ][i] == 1 )//position and value are both match
{
gr.ACount;
--g_count[ guessNumber[i]-'0' ];//reduce the count of the number
}
}
for( int i = 0; i < NUMBERS_GUESS; i )
{
if( g_buffer[ guessNumber[i]-'0' ][i] != 1
&& g_count[ guessNumber[i]-'0' ] > 0 )//just value match
{
gr.BCount;
--g_count[ guessNumber[i]-'0' ];
}
}
return gr;
}
void GenGuessNumber( char number[NUMBERS_GUESS 1] )
{
srand( time(NULL) );
for( int i = 0; i < NUMBERS_GUESS; i )
{
int num = rand() % NUMBERS_COUNT;
number[i] = num '0';
}
number[NUMBERS_GUESS] = '/0';
}
int main()
{
char originNumber[NUMBERS_GUESS 1];
char guessNumber[NUMBERS_GUESS 1];
GenGuessNumber( originNumber );
bool isGuessRight = false;
int guessCount = 0;
while( !isGuessRight )
{
cout<<"Please input the number you've guessed : "<<endl;
cin >> guessNumber;
if( Evaluate( originNumber, guessNumber ).ACount == NUMBERS_GUESS )
{
cout<<"You Are Greate!!!"<<endl;
cout<<"You've Guessed "<<guessCount<<" Times ."<<endl;
isGuessRight = true;
}
else
{
cout<<"The Result Is : "<<endl
<<Evaluate( originNumber, guessNumber )<<endl;
guessCount;
}
}
system( "pause" );
return 0;
}