UVA340 猜數字遊戲的提示 Master-Mind Hints

你的任務是實現一個經典的“猜數字”遊戲。給定答案序列和用戶猜的序列,統計有多少數字位置正確(設爲AA ),有多少數字在兩個序列中都出現過但位置不對(BB )。

輸入包含多組數據。每組輸入第一行爲序列長度nn ,第二行是答案序列,接下來是若干行猜測序列。猜測序列全00 時表示該組數據結束。n=0n=0 時輸入結束。

對於每一組數據,輸出的開頭應有一行**“Game x:”(沒有雙引號,x爲當前組數據的編號,從1開始遞增),然後對於每個猜測序列,輸出一組數,格式(A,B),A,B的意義如上所示,注意在(A,B)**之前要輸出四個空格符。

輸入輸出樣例
輸入 #1 複製
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
輸出 #1 複製
Game 1:
(1,1)
(2,0)
(1,2)
(1,2)
(4,0)
Game 2:
(2,4)
(3,2)
(5,0)
(7,0)


分析:(A,B)中A值爲與答案序列對應的位置正確的數字出現次數,設定兩個序列中出現相同數字的次數爲C,B=C-A;

#include<cstdio>
#include<iostream>
using namespace std;
const int N = 1000 +10 ;
int main(){
	int n, a[N],b[N];
	int kase = 0;
	while(scanf("%d",&n) == 1 && n){
		printf("Game %d:\n", ++kase);
		for(int i = 0; i< n; i++)
		scanf("%d",&a[i]);
		for(;;){
		
		int A = 0, B = 0;
		for(int i = 0;i < n;i++)
		{
			scanf("%d", &b[i]);
			if(a[i] == b[i])
			A++;
			
		 } 
		 if(b[0] == 0) break;// 正常的猜測序列不會有0,所以只判斷第一個數是否爲0即可
		 for(int d = 1; d <= 9;d++){
		 	int c1 = 0,c2 = 0;// 統計數字d在答案序列和猜測序列中各出現多少次
		 	for(int i = 0 ;i < n;i++)
		 	{
		 		if(a[i] == d) c1++;
		 		if(b[i] == d) c2++;
			 }
			 if(c1 < c2) 
			 B += c1; 
			 else 
			 B += c2; 
		 	
		 }
		 printf("   (%d,%d)\n",A,B-A); 
	}
}
	
	return 0;
} 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章