我几乎完成了我的公牛和奶牛项目但是如果我输入一个字母或数字序列,字母或数字重复,代码的“牛”部分就会混乱。举个例子:考虑以下
输入您希望有人猜到的内容:很酷
时间猜测!代码大小为4. book
COWS:0 BULLS:2
OZZO
COWS:4 BULLS:0
如您所见,进入“ozzo”后,牛的值应为2,而不是4。 如何在不更改整个代码的情况下解决此问题?
for (size_t i = 0; i != startg.getSize(); ++i){
if (guess[i] == origWord[i]){
bullCtr++;
} else {
for (size_t j = 0; j != startg.getSize(); ++j){
if (origWord[i] == guess[j]){
cowCtr++;
}
}
}
}
应用修复后的代码:
for (size_t i = 0; i != startg.getSize(); ++i){
if (guess[i] == origWord[i]){
bullCtr++;
} else {
for (size_t j = 0; j != startg.getSize(); ++j){
if (origWord[i] == guess[j]){
origWord[i] = 'X';
cowCtr++;
}
}
}
origWord = origWordcpy;
}
答案 0 :(得分:1)
你的奶牛检查有问题。
为了方便起见,我会做些什么(不完全是)(我只谈论其他陈述):
for(unsigned int j = 0 ; j != startg.getSize() ; j++)
{
if(origWord[i] == guess[j])
{
origWord[i] = 1; //Just assigning a certain value there to mark that we've already did something with it
cowCtr++;
}
}
那应该做的工作。
修改强>
你显然应该有一个临时字符串而不是origWord
因为更改它会影响外循环的下一次迭代(得到猜测并再次比较) - 我只是向你展示了方式。
答案 1 :(得分:0)
以下是 Bulls& amp;的一种可能的实施方式。奶牛游戏:
// used constants; numbers to be guessed
const int first_num = 2;
const int second_num = 4;
const int third_num = 1;
const int forth_num = 5;
int main(){
// vector holding the values to be guessed
vector<int>gamenum(4);
gamenum[0] = first_num;
gamenum[1] = second_num;
gamenum[2] = third_num;
gamenum[3] = forth_num;
// prompt message; input cycle till perfect guess (4 bulls)
int bulls = 0;
while (!(bulls == 4)){
// vector holding the guesses
vector<int>guesses;
// vector input values
int guess1(0), guess2(0), guess3(0), guess4(0);
cout << "\t\tPlay the game ""Bulls and Cows\n""" << endl;
cout << "Enter a set of four numbers, separated by whitespace space: ";
cin >> guess1 >> guess2 >> guess3 >> guess4;
guesses.push_back(guess1);
guesses.push_back(guess2);
guesses.push_back(guess3);
guesses.push_back(guess4);
// input confirmation; show your guess
cout << "\nYour guess is: ";
for (int i = 0; i < guesses.size(); ++i){
cout << guesses[i];
}
// bulls criterion
for (int j = 0; j < guesses.size(); ++j){
if (guesses[j] == gamenum[j]) ++bulls;
}
// cows criterion
int cows = 0;
for (int gue = 0; gue < guesses.size(); ++gue){
for (int gam = 0; gam < gamenum.size(); ++gam){
if (guesses[gue] == gamenum[gam] && gue != gam) ++cows;
}
}
// print result
if (bulls < 4){
cout << "\nBulls: " << bulls << " and Cows: " << cows <<endl;
cout << "\n\n\n" << endl;
// reset bulls
bulls = 0;
}
// empty guesses vector
guesses.clear();
// reset cows
cows = 0;
}
// print success
cout << "\nPerfect Guess!" << endl;
cout << "Bulls: " << bulls << endl;
cout << "\n\n\n" << endl;
keep_window_open();
return 0;
}
不是最佳的,不是最基本的,但是有效的。 您可以将其用作基准。