UVA489 - Hangman Judge

问题描述

 输入一个要猜测的答案字符串s,猜的字符串s2,判断猜测的字符错误次数为7次以内,7次以内并且全部猜中算赢,如果没猜中,则算放弃,如果错7次或以上则判定为输。

思路

进行比较字符时,将比较成功的字符改成空格,极大简化了步骤。

代码

紫书(《算法竞赛入门经典(第二版)》)中的代码简洁明了。

#include <iostream>
#include <cstdio>
#include <cstring>
#define maxn 100
using namespace std;
int Left, chance;       // 还需猜Left个位置,错chance次后就会输
char s[maxn],s2[maxn];  // 答案是字符串s,玩家猜出的字母序列为s2
int win,lose;           // win=1为赢,lose=1为输
void guess(char ch)
{
    int bad=1;
    for(int i=0;i<strlen(s);i++)
        if(s[i]==ch){Left--;s[i]=' ';bad=0;}
    if(bad)
        chance--;
    if(!chance)
        lose=1;
    if(!Left)
        win=1;
}
//判断成功后,更改字符为空格然后重新进行判断
int main()
{
    int rnd;
    while(cin>>rnd&&rnd!=-1)
    {
        scanf("%s%s",s,s2);
        printf("Round %d\n",rnd);
        win=lose=0;
        Left=strlen(s);
        chance=7;
        for(int i=0;i<strlen(s2);i++)
        {
            guess(s2[i]);
            if(win||lose)
                break;
        }
        if(win)
            printf("You win.\n");
        else if(lose)
            printf("You lose.\n");
        else
            printf("You chickened out.\n");

    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值