四川麻将胡牌判定(Python、C#、C++)

2023-05-16

**
一下是三种判定四川麻将(血战到底)胡牌的算法,主要思想是递归+回溯~

Python写法:

**

# -*- coding: utf-8 -*-
# @Time     :2022/2/18 14:15
# @Author   :LuoLin01


class PmaJong(object):
    def __init__(self):
        self.m_TypeNum = []
        self.m_CardNum = []
        self.HasCouple = False
        for i in range(3):
            self.m_TypeNum.append(0)
            self.m_CardNum.append([0]*9)

        self.g_typedef = ['w', 't', 'd']  # 万、条、筒
        self.m_GangNum = 0

    def InitData(self, cards_str):
        if not len(cards_str) or len(cards_str) % 2:  # 必然是偶数才能判断是否完成
            print("数据初始化出错")
            return

        cur_idx = 0
        while cur_idx < len(cards_str):
            cur_c = cards_str[cur_idx]

            nNum = ord(cur_c) - ord('0')
            cType = cards_str[cur_idx + 1]
            for i in range(3):
                if cType == self.g_typedef[i]:
                    self.m_TypeNum[i] += 1
                    self.m_CardNum[i][nNum - 1] += 1
                    break

            cur_idx += 2

    def IsSevenCouple(self):
        if 14 == self.m_TypeNum[0] + self.m_TypeNum[1] + self.m_TypeNum[2]:
            for i in range(3):
                for j in range(9):
                    if self.m_CardNum[i][j] != 0 and self.m_CardNum[i][j] != 2:
                        return False

    def IsWin(self):
        if self.m_TypeNum[0] and self.m_TypeNum[1] and self.m_TypeNum[2]:
            print("不是缺一门\n")
            return False
        if self.IsSevenCouple():
            print("七小对\n")
            return True

        for i in range(3):
            if not self.IsOneTypeWin(self.m_CardNum[i], self.m_TypeNum[i], i):
                print("花色:%s不满足胡牌\n" % self.g_typedef[i])
                return False

        if not self.HasCouple:
            print("没有对子,不能胡牌\n")
            return False

        if self.m_TypeNum[0] + self.m_TypeNum[1] + self.m_TypeNum[2] - 14 != self.m_GangNum:
            print("你丫诈和,牌的数量不对.\n")
            return False

        print("正常胡牌\n")
        return True

    def IsOneTypeWin(self, pCards, Num, type):
        print(pCards)
        if not Num:
            return True
        tmp = ""
        for i in range(9):
            if pCards[i] >= 2 and not self.HasCouple:
                pCards[i] -= 2
                self.HasCouple = True
                if self.IsOneTypeWin(pCards, Num - 2, type):
                    tmp += str(i+1) + self.g_typedef[type] + str(i+1) + self.g_typedef[type]
                    print("当前牌:%s\n", tmp)
                    return True
                pCards[i] += 2
                self.HasCouple = False

            if pCards[i] == 4:
                pCards[i] -= 4
                if self.IsOneTypeWin(pCards, Num - 4, type):
                    self.m_GangNum += 1
                    tmp += (str(i + 1) + self.g_typedef[type]) * 4
                    print("当前牌:%s\n", tmp)
                    return True
                pCards[i] += 4

            if pCards[i] >= 3:
                pCards[i] -= 3
                if self.IsOneTypeWin(pCards, Num - 3, type):
                    tmp += (str(i + 1) + self.g_typedef[type]) * 3
                    print("当前牌:%s\n", tmp)
                    return True
                pCards[i] += 3

            if i < 7 and pCards[i] and pCards[i + 1] and pCards[i + 2]:
                pCards[i] -= 1
                pCards[i + 1] -= 1
                pCards[i + 2] -= 1
                if self.IsOneTypeWin(pCards, Num - 3, type):
                    tmp += str(i + 1) + self.g_typedef[type] + str(i + 2) + self.g_typedef[type] + str(i + 3) + self.g_typedef[type]
                    print("当前牌:%s\n", tmp)
                    return True
                pCards[i] += 1
                pCards[i + 1] += 1
                pCards[i + 2] += 1

        return False


if __name__ == "__main__":
    cur_s = "1w1w1w2d3d4d2w3w4w7d8d9d5w5w"
    mahJong = PmaJong()
    mahJong.InitData(cur_s)
    if mahJong.IsWin():
        print("win !!!!!")
    else:
        print("False !!!!!")


## c#写法

using System;
namespace ConsoleApp1
{
    class CSMahJangg
    {
        public CSMahJangg()
        {

        }
        public int[] m_TypeNum = new int[3];
        public int[][] m_CardNum =
            {
            new int[9],
            new int[9],
            new int[9],
        };
        public int m_GangNum = 0;
        public char[] g_typedef = new char[] { 'w', 't', 'd' };

        public void Init(string pCards)
        {
            int cur_idx = 0;

            char pTmp = pCards[cur_idx];
            int nNum = 0;
            char cType;
            while (cur_idx < pCards.Length)
            {
                pTmp = pCards[cur_idx];
                nNum = pTmp - '0';
                cType = pCards[cur_idx+1];
                for (int i = 0; i < 3; i++)
                {
                    if (cType == g_typedef[i])
                    {
                        m_TypeNum[i]++;
                        m_CardNum[i][nNum - 1]++;
                        break;
                    }
                }
                cur_idx += 2;
            }
        }

        public bool IsSevenCouple()
        {
            if (14 == m_TypeNum[0] + m_TypeNum[1] + m_TypeNum[2])
            {
                for (int i = 0; i < 3; i++)
                {
                    for (int j = 0; j < 9; j++)
                    {
                        if (m_CardNum[i][j] != 0 && m_CardNum[i][j] != 2)
                        {
                            return false;
                        }
                    }
                }
                return true;
            }
            return false;
        }

        public bool IsWin()
        {
            if (m_TypeNum[0] > 0 && m_TypeNum[1] > 0 && m_TypeNum[2] > 0)
            {
                //不是缺一门
                Console.WriteLine("不是缺一门\n");
                return false;
            }
            if (IsSevenCouple())
            {
                //七小对
                Console.WriteLine("七小对\n");
                return true;
            }
            //正常胡牌:有一个对子,其余的要么三支顺子,要么三支一样的(或四只)
            bool HasCouple = false;
            for (int i = 0; i < 3; i++)
            {
                if (!IsOneTypeWin(m_CardNum[i], m_TypeNum[i], ref HasCouple, i))
                {
                    Console.WriteLine("花色:{0}不满足胡牌\n", g_typedef[i]);
                    return false;
                }
            }
            if (!HasCouple)
            {
                Console.WriteLine("没有对子,不能胡牌\n");
                return false;
            }
            if (m_TypeNum[0] + m_TypeNum[1] + m_TypeNum[2] - 14 != m_GangNum)
            {
                Console.WriteLine("你丫诈和,牌的数量不对.\n");
                return false;
            }
            Console.WriteLine("正常胡牌\n");
            return true;
        }

        public bool IsOneTypeWin(int [] pCards, int Num, ref bool HasCouple, int type) // 递归回溯求解
        {
            if (Num == 0)
            {
                return true;
            }
            string tmp = "";
            for (int i = 0; i < 9; i++)
            {
                if (pCards[i] >= 2 && !HasCouple)
                {
                    pCards[i] -= 2;
                    HasCouple = true;
                    if (IsOneTypeWin(pCards, Num - 2, ref HasCouple, type))
                    {
                        tmp += Convert.ToString(i + 1) + g_typedef[type] + Convert.ToString(i + 1) + g_typedef[type];
                        Console.WriteLine("当前牌:{0}\n", tmp);
                        return true;
                    }
                    pCards[i] += 2;
                    HasCouple = false;
                }
                if (pCards[i] == 4) // 有四个一样的
                {
                    pCards[i] -= 4;
                    if (IsOneTypeWin(pCards, Num - 4, ref HasCouple, type))
                    {
                        tmp += Convert.ToString(i + 1) + g_typedef[type] + Convert.ToString(i + 1) + g_typedef[type] +
                            Convert.ToString(i + 1) + g_typedef[type] + Convert.ToString(i + 1) + g_typedef[type];
                        Console.WriteLine("当前牌:{0}\n", tmp);
                        m_GangNum++;
                        return true;
                    }
                    pCards[i] += 4;
                }
                if (pCards[i] >= 3)
                {
                    pCards[i] -= 3;
                    if (IsOneTypeWin(pCards, Num - 3, ref HasCouple, type))
                    {
                        tmp += Convert.ToString(i + 1) + g_typedef[type] + Convert.ToString(i + 1) + g_typedef[type] +
                            Convert.ToString(i + 1) + g_typedef[type] ;
                        Console.WriteLine("当前牌:{0}\n", tmp);
                        return true;
                    }
                    pCards[i] += 3;
                }
                if (i < 7 && pCards[i]>0 && pCards[i + 1]>0 && pCards[i + 2]>0) // 顺子
                {
                    pCards[i] -= 1;
                    pCards[i + 1] -= 1;
                    pCards[i + 2] -= 1;
                    if (IsOneTypeWin(pCards, Num - 3, ref HasCouple, type))
                    {
                        tmp += Convert.ToString(i + 1) + g_typedef[type] + Convert.ToString(i + 2) + g_typedef[type] +
                            Convert.ToString(i + 1) + g_typedef[type] + Convert.ToString(i + 3) + g_typedef[type];
                        Console.WriteLine("当前牌:{0}\n", "123");
                        return true;
                    }
                    pCards[i] += 1;
                    pCards[i + 1] += 1;
                    pCards[i + 2] += 1;
                }
            }
            return false;
        }



    }

    class Program
    {
        static void Main(string[] args)
        {
            CSMahJangg mj = new CSMahJangg();
            string s = "2d1w1w1w2d3d4d2w3w4w7d8d9d5w5w";
            mj.Init(s);
            Console.WriteLine("当前牌:{0}\n", "123");
            if (mj.IsWin())
            {
                Console.WriteLine("Win!!!!!");
            }
            else
            {
                Console.WriteLine("False!!!!!");
            }



            Console.ReadKey();

        }
    }
}

**

c++写法

**

#include <stdio.h>
#include <cstring>
#include<iostream>
#include <vector>
#define TEST 0
#if TEST
#define LOG(fmt, ...) printf("line=%d file=%s" fmt"\n",  __LINE__, __FILE__, ##__VA_ARGS__)
#else
#define LOG(fmt, ...) printf( fmt"\n", ##__VA_ARGS__)
#endif
using std::vector;

const char g_typedef[3] = { 'w', 't', 'd' };//万、条、筒


class CMahJangg
{
public:
	CMahJangg()
	{
		m_TypeNum = vector<int>(3, 0);
		m_CardNum = vector<vector<int>>(3, vector<int>(9));
		for (int i = 0; i < 3; i++)
		{
			m_TypeNum[i] = 0;
			memset(log, 0, sizeof(char) * 100);
			m_GangNum = 0;  
		}

	}
	void Init(char *pCards)
	{
		char *pTmp = pCards;
		int nNum = 0;
		char cType = 0;
		while (*pTmp != '\0')
		{
			nNum = *pTmp - '0';
			cType = *(pTmp + 1);
			for (int i = 0; i < 3; i++)
			{
				if (cType == g_typedef[i])
				{
					m_TypeNum[i]++;
					m_CardNum[i][nNum - 1]++;
					break;
				}
			}
			pTmp += 2;
		}
	}
	bool IsSevenCouple()
	{
		if (14 == m_TypeNum[0] + m_TypeNum[1] + m_TypeNum[2])
		{
			for (int i = 0; i < 3; i++)
			{
				for (int j = 0; j < 9; j++)
				{
					if (m_CardNum[i][j] != 0 && m_CardNum[i][j] != 2)
					{
						return false;
					}
				}
			}
			return true;
		}
		return false;
	}
	bool IsWin()
	{
		if (m_TypeNum[0] && m_TypeNum[1] && m_TypeNum[2])
		{
			//不是缺一门
			LOG("不是缺一门\n");
			return false;
		}
		if (IsSevenCouple())
		{
			//七小对
			LOG("七小对\n");
			return true;
		}
		//正常胡牌:有一个对子,其余的要么三支顺子,要么三支一样的(或四只)
		bool HasCouple = false;
		for (int i = 0; i < 3; i++)
		{
			if (!IsOneTypeWin(m_CardNum[i], m_TypeNum[i], HasCouple, i))
			{
				LOG("花色:%c不满足胡牌\n", g_typedef[i]);
				return false;
			}
		}
		if (!HasCouple)
		{
			LOG("没有对子,不能胡牌\n");
			return false;
		}
		if (m_TypeNum[0] + m_TypeNum[1] + m_TypeNum[2] - 14 != m_GangNum)
		{
			LOG("你丫诈和,牌的数量不对.\n");
			return false;
		}
		LOG("正常胡牌\n");
		return true;
	}
	void Print(vector<int> pCards, int type)
	{
		char t = g_typedef[type];
		for (int i=0; i<9; i++ )
		{
			for (int j = 0; j < pCards[i]; j++)
			{
				std::cout << i+1 << "" << t << " ";
			}
			
		}
		std::cout << std::endl;
	}
	bool IsOneTypeWin(vector<int> pCards, int Num, bool &HasCouple, int type) // 递归回溯求解
	{
		Print(pCards, type);
		if (Num == 0)
		{
			return true;
		}
		char tmp[20] = { 0 };
		for (int i = 0; i < 9; i++)
		{
			if (pCards[i] >= 2 && !HasCouple)
			{
				pCards[i] -= 2;
				HasCouple = true;
				if (IsOneTypeWin(pCards, Num - 2, HasCouple, type))
				{
					sprintf(tmp, "%d%c%d%c ", i + 1, g_typedef[type], i + 1, g_typedef[type]);
					strcat(log, tmp);
					LOG("当前牌:%s\n", log);
					return true;
				}
				pCards[i] += 2;
				HasCouple = false;
			}
			if (pCards[i] == 4) // 有四个一样的
			{
				pCards[i] -= 4;
				if (IsOneTypeWin(pCards, Num - 4, HasCouple, type))
				{
					sprintf(tmp, "%d%c%d%c%d%c%d%c ", i + 1, g_typedef[type], i + 1, g_typedef[type], i + 1, g_typedef[type], i + 1, g_typedef[type]);
					strcat(log, tmp);
					LOG("当前牌:%s\n", log);
					m_GangNum++;
					return true;
				}
				pCards[i] += 4;
			}
			if (pCards[i] >= 3)
			{
				pCards[i] -= 3;
				if (IsOneTypeWin(pCards, Num - 3, HasCouple, type))
				{
					sprintf(tmp, "%d%c%d%c%d%c ", i + 1, g_typedef[type], i + 1, g_typedef[type], i + 1, g_typedef[type]);
					strcat(log, tmp);
					LOG("当前牌:%s\n", log);
					return true;
				}
				pCards[i] += 3;
			}
			if (i < 7 && pCards[i] && pCards[i + 1] && pCards[i + 2]) // 顺子
			{
				pCards[i] -= 1;
				pCards[i + 1] -= 1;
				pCards[i + 2] -= 1;
				if (IsOneTypeWin(pCards, Num - 3, HasCouple, type))
				{
					sprintf(tmp, "%d%c%d%c%d%c ", i + 1, g_typedef[type], i + 2, g_typedef[type], i + 3, g_typedef[type]);
					strcat(log, tmp);
					LOG("当前牌:%s\n", log);
					return true;
				}
				pCards[i] += 1;
				pCards[i + 1] += 1;
				pCards[i + 2] += 1;
			}
		}
		return false;
	}

private:
	vector<int> m_TypeNum;
	vector<vector<int>> m_CardNum;
	int m_GangNum;  // 杠的数量
	char log[100];  //用作打印log
};
bool IsMahJangWin(char *pCard)
{
	CMahJangg mj;
	mj.Init(pCard);
	return mj.IsWin();
}

int main()
{
	char a[100] = "1w1w1w2d3d4d2w3w4w7d8d9d5w5w";
	auto r = IsMahJangWin(a);
	if (r)
	{
		LOG("win!!!!!");
	}
	else
	{
		LOG("Not Win!!!!");
	}
	return 0;
}

以上三种写法都可以运行,需要自取,不懂留言,有空看到尽力回复~

ps:每天都要进步,蛰伏,当遇到风口浪尖,希望能够随风起飞

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

四川麻将胡牌判定(Python、C#、C++) 的相关文章

  • 嵌入式工程师职业生涯该怎样规划

    嵌入式工程师分布在各行各业 xff0c 包括消费电子 工业电子 汽车电子和军用电子等 从功能上面看 xff0c 嵌入式本身包括了51 mcu soc soc 43 baseband等很多形式 从开发的结构上看 xff0c 有些同学专注于底层
  • 使用ros实现c++与python通信

    创建工作空间 选择在桌面创建 cd mkdir p my workspace src 编译工作空间 cd my workspace catkin make source一下新生成的setup bash文件 xff1a source deve
  • C++输出系统时间

    编译软件 xff1a dev5 4 0 程序功能 xff1a 输出系统时间 xff0c 输出格式 2018 08 10 15 14 40 方法 xff1a 使用time t获取系统时间 xff0c 再使用strftime 函数对日期和时间进
  • 该博客已搬家至 博客园

    由于CSDN不支持metaweblog xff0c 该博客今日起停止更新 所有内容移至博客园 我的博客园博客地址 xff1a 戳我 https www cnblogs com wittxie CSDN写文章真的难受 xff0c 具体原因你们
  • Kernel Based Progressive Distillation for Adder Neural Networks:基于核的渐进式蒸馏的加法神经网络

    2020 NeurIPS AdderNet基于核的渐进式的蒸馏加法神经网络 一 简介二 问题解决2 1问题提出2 2初步解决方案2 3具体分析2 4问题解决 用核方法来解决这个问题2 5渐进式学习 三 实验结果分析3 1基于MNIST数据集
  • 人脸识别 灰度化

    人脸识别 灰度化 欢迎使用Markdown编辑器 你好 xff01 这是你第一次使用 Markdown编辑器 所展示的欢迎页 如果你想学习如何使用Markdown编辑器 可以仔细阅读这篇文章 xff0c 了解一下Markdown的基本语法知
  • 基于STM32F103的红外遥控小车

    本人小白一个 xff0c 利用空闲时间 xff0c 做了一些小东西 xff0c 跟大家分享一下自己的代码 如有不对的地方 xff0c 还请各位前辈指正 话不多说 xff0c 先上干货 include 34 remote h 34 inclu
  • 关于realsense d435i的安装步骤及问题总结

    一 realsense的安装过程 参考链接 xff1a 1 Ubuntu18 04 安装D435i ROS 2 Ubuntu下Realsense SDK的安装 3 Realsense D435i 在ubuntu上安装SDK与ROS Wrap
  • ROS编译catkin_make的时候报错找不到xxx.h头文件

    报错内容 xff1a home firefly eai ws src square square goal service src service server cpp 3 53 fatal error square goal servic
  • Ubuntu下安装GParted并分区,进行虚拟机内存扩展

    首先对于虚拟机下的Ubuntu系统安装Gparted 直接使用sudo apt get install gparted 关机先进行内存分配后 xff0c 再进行下面操作 网上还有其他适合的教程 xff0c 我的16 04这样安装是没问题的
  • PIP版本过低,更新无用,Command “python setup.py egg_info“ failed with error code 1 in报错

    Ubuntu下pip install 时候python2 7总是报错 Complete output from command python setup py egg info Traceback most recent call last
  • 小觅双目相机进行ROS标定

    安装image pipeline包 使用ROS官方提供的 camera calibration 包对双目相机进行标定 详情可见官网camera calibration Tutorials StereoCalibration ROS Wiki
  • ubuntu18.04安装ORB_SLAM3以及遇到的问题

    目录 1 安装c 43 43 11 2 安装Pangolin a xff09 安装依赖 b xff09 编译pangolin 切换到pangolin下载包里面 3 安装opencv 4 eigen3安装 5 boost安装 6 编译ORB
  • 【论文写作】Word中公式快捷输入方式

    环境 Win10 64位 用到软件 Mirsoft Word MathType Mathpix snipping tool Quicker 说明 xff1a 点击链接可以直达官网 一 前言 针对Word中公式输入效率低的问题 xff0c 本
  • 练习7-10 查找指定字符 (15分)

    本题要求编写程序 xff0c 从给定字符串中查找某指定的字符 输入格式 xff1a 输入的第一行是一个待查找的字符 第二行是一个以回车结束的非空字符串 xff08 不超过80个字符 xff09 输出格式 xff1a 如果找到 xff0c 在
  • 用cropper.js裁剪图片并上传到服务器,解析base64转存图片到本地

    今天要写上传图片功能 xff0c 研究了一下cropper 将图片上传服务器并保存到本地 html lt html gt lt head gt lt title gt 基于cropper js的图片裁剪 lt title gt lt met
  • 通讯协议详解

    1 xff0c 概念 网络协议指的是计算机网络中互相通信的对等实体之间交换信息时所必须遵守的规则的集合 网络上的计算机之间是如何交换信息的呢 xff1f 就像我们说话用某种语言一样 xff0c 在网络上的各台计算机之间也有一种语言 xff0
  • 自动识别击打控制系统

    目录 摘 要 关键词 一 系统方案 1 1 系统基本方案 1 2 程序算法的具体流程 二 视觉程序识别框架 2 1多线程 2 2 opencv配置文件 2 3 主函数 三 装甲板识别算法 3 1 装甲板识别 3 2 识别函数介绍 四 目标位
  • 基于stm32风力摆控制系统(电赛获得省一)

    目录 需要源文档及程序进入主页 一 系统方案 完整文档以及代码可主页私 1 1 系统基本方案 1 1 1 控制方案设计 1 1 2 机械结构方案设计
  • 基于stm32的所有嵌入式项目代码

    nbsp nbsp nbsp nbsp nbsp nbsp nbsp nbsp 本人本科和硕士阶段的专业都是嵌入式方向 做了许许多多的项目 包括51 stm32 freeRTOS linux操作系统 多进程线程实现功能 包括裸机开发 驱动开

随机推荐