【算法基础】循环相克令(猜拳游戏)

在这里插入图片描述

👦个人主页:Weraphael
✍🏻作者简介:目前正在学习c++和算法
✈️专栏:【C/C++】算法
🐋 希望大家多多支持,咱一起进步!😁
如果文章有啥瑕疵
希望大佬指点一二
如果文章对你有帮助的话
欢迎 评论💬 点赞👍🏻 收藏 📂 加关注😍


一、题目描述

在这里插入图片描述

二、朴树思路及代码实现

可能很多人一开始写就是嵌套if-else代码如下:(本人也一样)

#include <iostream>
#include <cstring>
using namespace std;

int main()
{
    int t;
    cin >> t;

    while (t--)
    {
        string a, b;
        cin >> a >> b;

        if (a == "Hunter")
        {
            if (b == "Hunter")
            {
                cout << "Tie" << endl;
            }
            else if (b == "Bear")
            {
                cout << "Player2" << endl;
            }
            else cout << "Player1" << endl;
        }
        else if (a == "Bear")
        {
            if (b == "Hunter")
            {
                cout << "Player1" << endl;
            }
            else if (b == "Bear")
            {
                cout << "Tie" << endl;
            }
            else cout << "Player2" << endl;
        }
        else // a == Gun
        {
            if (b == "Hunter")
            {
                cout << "Player2" << endl;
            }
            else if (b == "Bear")
            {
                cout << "Player1" << endl;
            }
            else cout << "Tie" << endl;
        }
    }
    return 0;
}

三、优雅思想和代码实现

后来听了y总的思路:我们可以将Player1Player2的所有可能性映射成数字,例如,Hunter记作0Gun记作1Bear记作2 。然后根据题目意思:猎人赢枪、枪赢狗熊、狗熊赢猎人,可以得出以下关系:

player1    player2
   0   ->    1
   1   ->    2
   2   ->    0
// -> 代表赢

然后我们可以发现一些规律:

  1. 如果player1 == player2代表平局Tie
  2. 如果(Player1 + 1) % 3 == Player2的话,就代表Player1
  3. 如果不包含以上两种情况,则Player2

于是可以写出以下【优雅代码】

#include <string>
#include <iostream>
using namespace std;

int main()
{
    int t;
    cin >> t;
    
    while (t --)
    {
        string a, b;
        cin >> a >> b;
        
        int x, y;
        if (a == "Hunter") x = 0;
        else if (a == "Gun") x = 1;
        else x = 2;
        
        if (b == "Hunter") y = 0;
        else if (b == "Gun") y = 1;
        else y = 2;
        
        if (x == y) puts("Tie");
        else if ((x + 1) % 3 == y) puts("Player1");
        else puts("Player2");
    }
    return 0;
}
  • 11
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值