首页 > 技术文章 > 【C/C++】例题 4-2 刽子手游戏/算法竞赛入门经典/函数和递归

kinologic 2020-11-18 21:44 原文

【题目】
猜单词游戏。
计算机想一个单词让你猜,你每次猜一个字母。
如果单词里有那个【字母】,【所有该字母会显示出来】。
如果没有那个字母,算猜错一次。【最多只能猜错六次】
猜一个已经猜过的字母也算错。

【样例输入】
1
cheese
chese
2
cheese
abcdefg
3
cheese
abcdefgij
-1

【样例输出】
Round 1
You win.
Round 2
You chickened out.
Round 3
You lose.

【思路】
为了实现“如果单词里有那个【字母】,【所有该字母会显示出来】。猜一个已经猜过的字母也算错。”的需求:
先看计算机的问题串中是否有这个字母,如果有,把所有这个字母都换成空格。
遍历串2的每一个字母,对于每一个字母,读取字母,看这个字母在串1中是否存在(遍历串1).再执行如上操作。
chickened out 和 win 的区别是 chickened out没有把问题串中所有字都覆盖到。尽管二者的错误都小于7.

【代码】

#include <iostream>
#include <cstdlib>
#include <string.h>
using namespace std;
const int maxn = 25;
char* message[] = {"You win.", "You lose.", "You chickened out."};

void guess(char a, char str[], int len, int& wrong)
{
    //考虑读入进来的字符,是不是在题目串中存在
    int flag = 0;
    //char temp;
    for (int i = 0; i < len; i++)
    {
        if (str[i] == a)
        {
            flag = 1; 
            break;
        }
        //cout << i <<"wrong" << wrong << endl;
    }
    //如果在题目串中存在,将所有字符换成空格
    if (flag)
    {
        for (int i = 0; i < len; i++)
        {
            if (str[i] == a)
            {
                str[i] = ' ';
            }
        }
    }
    else
    {
        wrong++;
    }
}

int main()
{
    int n;
    //数组s_ques为计算机猜测,s_ans为用户猜测
    char s_ques[maxn], s_ans[maxn];
    //考虑一组输入
    while(scanf("%d%s%s",&n, &s_ques, &s_ans) == 3 && n != (-1))
    {
        int wrong = 0;
        printf("Round %d\n", n);
        int len1 = strlen(s_ques);
        int len2 = strlen(s_ans);
        for (int i = 0; i < len2; i++)
        {
            guess(s_ans[i], s_ques, len1, wrong);
        }
        int cnt = 0;
        for (int i = 0; i < len1; i++)
        {
            if (s_ques[i] == ' ') cnt++; 
        }
        if (wrong < 7 && cnt == len1)
        {
            cout << message[0] << endl;
        }
        else if (wrong > 6)
        {
            cout << message[1] << endl;
        }
        else 
        {
            cout << message[2] << endl;
        }
    }

    system("pause");
}

推荐阅读