#include <iostream>
#include <time.h>
#include <limits>

using namespace std;

int main()
{
	short Ans[4] = {0};
	short Guess[4] = {0};
	short Input = 0, A = 0, B = 0, i = 0, j = 0, count = 0;
	char GoOn = ' ';

	cout << "這是猜數字遊戲範例，程式會隨機給出一個數字，其為" << endl
		 << "0~9中任意4個不重複數的組合，例：1234、3980、0657" << endl
		 << "請你隨意輸入你想到的組合，程式回應你有猜中幾個數" << endl
		 << "字，如果猜中數字，會說有幾個B，如果猜中數字的同時" << endl
		 << "也猜中了它的位置，會說有幾個A，例如程式給的數字是" << endl
		 << "1234，你猜8240，那就是1A1B，A是2，B是4。" << endl;
	
	system( "pause" );

	srand( (unsigned)time( NULL ) );

	do{		// 遊戲迴圈
		system( "cls" );
		count = 0;	// 每場遊戲要重新計算猜測次數
		A = 0;	// 因為A == 4為猜對的條件，所以在此必須歸零才能再度進入猜測迴圈中

// **************隨機產生不重複之四個數字***********************
        for( i = 0; i < 4; i++ )
			Ans[i] = rand() % 10;
	
		while( Ans[1] == Ans[0] )
		{
			Ans[1] = rand() % 10;
		}
	
		while( Ans[2] == Ans[1] || Ans[2] == Ans[0] )
		{
			Ans[2] = rand() % 10;
		}
	    
		while( Ans[3] == Ans[2] || Ans[3] == Ans[1] || Ans[3] == Ans[0] )
		{
			Ans[3] = rand() % 10;
		}
// *************************************************************

		while( A < 4 )	// 猜測迴圈
		{
			A = 0;	// 每次猜測必須把A跟B歸零
			B = 0;

			while( 1 )	// 無限迴圈
			{
Repeat:
				cout << "請輸入你的猜測：";
				cin >> Input;
		
				if( cin.fail() )
				{ 
					cin.clear();
					cin.ignore( numeric_limits<streamsize>::max(), '\n' );
					cout << "錯誤的輸入格式！" << endl;
					continue;
				}
		
				// 因為四個數字不能重複，所以最小為0123，最大為9876，存成數字型態，則0123的0可省略
				if( Input >= 123 && Input <= 9876 )
				{
					// 如果( 1000 / pow( 10, i ) )沒括號起來，變成Input / 1000 * pow( 10, i );
					// 則Input先除1000，百位數以下都會消失，不會得到正確的數值
					// 若改成Input * pow( 10, i ) / 1000;，應該是可以，但可能會有overflow的危險
					for( i = 0; i < 4; i++ )
					{
						Guess[i] = Input / ( 1000 / (int)pow( 10, i ) );
						Input -= Guess[i] * (int)pow( 10, 3 - i );	// 減掉較高位數的數字
					}
	
					for( i = 0; i < 4; i++ )
						for( j = 0; j < 4; j++ )
							if( Guess[j] == Guess[i] && i != j )
							{
								cout << "輸入的四位數中不可有重複的數字出現！" << endl;
								goto Repeat;
							}

					break;	// 跳出無限迴圈
				}
				else
				{
					cout << "請輸入四位數字！" << endl;
				}
			}		
			
			for( i = 0; i < 4; i++ )
				for( j = 0; j < 4; j++ )
				{
					if( Guess[j] == Ans[i] )	// 數字相同
					{
						if( i == j )	// 位置一樣
							A++;
						else			// 位置不同
							B++;
					}
				}
	
			count++;
		
			if( A == 4 )
			{
				cout << "恭喜你！猜對了！共猜了 " << count << " 次" << endl;
				cout << "要繼續玩嗎？(y/n) ";
				cin >> GoOn;
			}
			else
			{
		        cout << A << " A " << B << " B" << endl;
			}
		}
	}while( GoOn == 'y' || GoOn == 'Y' );
	
	return 0;
}