#include <iostream>
#include <stdio.h>
#include <vector>
#include <string>
#include <map>
using namespace std;
/*
问题:珠玑妙算游戏的玩法如下。
计算机有4个槽,每个槽坊一个球,颜色可能是红色(R)、黄色(Y)、绿色(G)或蓝色(B)。例如计算机可能有RGGB四种(槽1位红色,槽2、3位绿色,槽4位蓝色)。
作为用户,你视图猜出颜色组合。打个比方,你可能会猜YRGB。
要是猜对某个槽的颜色,则算一次“猜中”;要是只猜对颜色但槽位猜错了,则算一次“伪猜中”。注意:猜中不能算入伪猜中。
举个例子,实际有颜色组合为RGBY,而你猜的是GGRR,则算一次猜中,一次伪猜中。
给定一个猜测和一种颜色组合,编写一个方法,返回猜中和伪猜中的次数。
分析:该题目可以这样做,我们把猜中的那个槽对应的颜色,从实际颜色组合和猜的颜色组合中都划掉,返回正确猜中次数。
比如实际有颜色组合为RGBY,而你猜的是GGRR,因为猜中第二个槽,所以划掉第二个槽,得到
实际有颜色组合为RBY,而你猜的是GRR,然后接下来可以针对实际颜色组合建立一个map<颜色, 0>,
然后遍历我猜的颜色中,
1】如果我猜的颜色不在map中,就不累加;
2】如果在map中,且对应值为0,说明是第一次统计该颜色的伪猜中次数,则累加伪猜中次数,并修改该map中颜色对应的值为1;
3】如果在map中,且对应值为1,说明该颜色的伪猜中次数之前机已经统计过了,则不处理
输入:
GGRR(猜测颜色组合) RGBY(实际颜色组合)
输出:
1(猜中次数) 1(伪猜中次数)
*/
//返回实际猜中次数和伪猜中次数
pair<int , int> countGuessTimes(string& guessColors , string& realColors)
{
if(guessColors.empty() || realColors.empty() || guessColors.length() != realColors.length())
{
pair<int , int> result(0,0);
return result;
}
int guessTimes = 0;
int fakeGuessTimes = 0;
string deleteString = guessColors;
int size = guessColors.length();
typedef map<char , int> ColorMap;
ColorMap colorMap;
for(int i = 0 ; i < size ; i++)
{
deleteString.at(i) = ' ';
//如果颜色相同,就删除当前颜色,并累加实际猜中次数
if( guessColors.at(i) == realColors.at(i) )
{
guessTimes++;
deleteString.at(i) = '1';
}
//颜色不同,就对实际颜色建立map
else
{
colorMap.insert(pair<char , int>(realColors.at(i) , 0));
}
}
//再次遍历猜测字符串,统计伪猜中次数
ColorMap::iterator it;
for(int i = 0 ; i < size ; i++)
{
//过滤掉猜中的颜色
if('1' == deleteString.at(i))
{
continue;
}
char color = guessColors.at(i);
it = colorMap.find(color);
if(it != colorMap.end())
{
if(it->second == 0)
{
fakeGuessTimes++;
//修改值,防止下次重复统计
it->second = 1;
}
}
}
pair<int , int> result(guessTimes , fakeGuessTimes);
return result;
}
void process()
{
string guessColors;
string realColors;
pair<int , int> result;
while(cin >> guessColors >> realColors)
{
result = countGuessTimes(guessColors , realColors);
cout << result.first << " " << result.second << endl;
}
}
int main(int argc , char* argv[])
{
process();
getchar();
return 0;
}
程序员面试金典——解题总结: 9.17中等难题 17.5珠玑妙算游戏
最新推荐文章于 2024-03-04 16:19:39 发布