Table of Contents
Q question
Cause
Game rules:
The rules for card types are as follows:
Input description:
Output description:
Input example:
Output example:
A solution
1 .Logical analysis
2. Analysis of difficulties
3. Code implementation
Run the test
Home Java javaTutorial How to implement the Zha Jinhua game with code

How to implement the Zha Jinhua game with code

Jun 26, 2017 pm 02:10 PM
staff Sohu algorithm interview

Zha Jinhua is a small game, I want to be a programmer. Most of them have played it when they were children! Now let’s take a look at this Sohu interview question! See how to use code to implement Zha Jinhua.


Q question

Cause

两个搜狐的程序员加了一个月班,终于放假了,于是他们决定扎金花渡过愉快的假期 。
Copy after login

Game rules:

There are 52 ordinary cards in total. The cards are one of 2, 3, 4, 5, 6, 7, 8, 9, 10, J, Q, K, and A. The size is increasing. Four; each player draws three cards. The two people compare the three cards in their hands, and the person with the bigger card wins.

The rules for card types are as follows:

  • 1. Three cards that are the same are leopards

  • 2. Three consecutive cards form a straight (A23 does not count as a straight)

  • 3. There are only two cards that are the same pair. Leopard > Straight > Pair > Ordinary card types. When the card types are the same, compare the numerical values ​​of the card types (such as AAA>KKK, QAK>534, QQ2> ;10104) When neither player has a special card type, compare the highest among the three cards in turn. The person with the bigger card wins. If the highest card is the same, the second highest card will be compared, and so on (such as 37K>89Q). If the two cards are the same, it will be a draw.

Input description:

输入两个字符串代表两个玩家的牌(如”10KQ” “354”),
先输入的作为玩家1,后输入的作为玩家2
Copy after login

Output description:

 1 代表 玩家1赢     
 0 代表 平局   
 -1 代表 玩家2赢 
 -2 代表不合法的输入
Copy after login

Input example:

KQ3 3Q9
10QA 6102
5810 7KK
632 74J
10102 K77
JKJ 926
68K 27A
Copy after login

Output example:

1
1
-1
-1
1
1
-1
Copy after login

A solution

1 .Logical analysis

  • (1) Get the strings input by players 1 and 2 and determine whether they are legal

  • (2) After it is legal, split the string into a string array

  • (3) Convert the string array into an int array and sort

  • ( 4) Determine the equality of 3 cards

  • (5) Compare the big and small, who loses and who wins

2. Analysis of difficulties

  • When there is 10, the problem of string splitting: you can judge the splitting according to the length of the string

  • Convert the letters For numbers: First convert all the strings you get to uppercase, so that the lowercase and uppercase letters are the same, and then directly use if to judge the return

  • Compare who loses and who wins : Use the method from big to small to compare, first judge whether there is a leopard, then judge the straight, then judge the pair, and finally judge the problem of handling the straight with no card type

3. Code implementation

package 搜狐面试2016;

import java.util.Arrays;
import java.util.Scanner;

public class Test1 {
    public static void main(String[] args) {
        // 2,3,4,5,6,7,8,9,10,J,Q,K,A
        Scanner scanner = new Scanner(System.in);
        boolean isContinue=true;
        while (isContinue) {
            //1.游戏规则
            System.out.println("游戏规则:共52张普通牌,牌面为2,3,4,5,6,7,8,9,10,J,Q,K,A之一,大小递增,各四张; 每人抓三张牌。两人比较手中三张牌大小,大的人获胜。");
            System.out.println("对于牌型的规则如下:");
            System.out.println("1.三张牌一样即为豹子");
            System.out.println("2.三张牌相连为顺子(A23不算顺子)");
            System.out.println("3.有且仅有两张牌一样为对子 豹子>顺子>对子>普通牌型 在牌型一样时,比较牌型数值大小");
            System.out.println("谁输谁赢:1 --代表玩家1赢;0 --代表 平局   ;-1 --代表玩家2赢 ;-2 --代表不合法的输入");
             
            //2.分别出牌
            System.out.println("请玩家1出牌:");
            String num1 = scanner.next();
            System.out.println("请玩家2出牌:");
            String num2 = scanner.next();
            
            //3.判断是否合法
            boolean flag=isValid(num1, num2);
            if(!flag){
                //不合法
                System.out.println("-2");
            }else {
                //输入合法---先拆分字符串---再转化为int数组
                //4.拆分字符串
                String[] nums1=getStrArray(num1);
                String[] nums2=getStrArray(num2);
                System.out.println("拆分后的字符串数组A:"+Arrays.toString(nums1));
                System.out.println("拆分后的字符串数组B:"+Arrays.toString(nums2));
                
                //5.转化为int数组
                int[] nums11=strToNumber(nums1);
                int[] nums22=strToNumber(nums2);
                System.out.println("转化为int后的数组A:"+Arrays.toString(nums11));
                System.out.println("转化为int后的数组B:"+Arrays.toString(nums22));
                
                //6.获得三张牌的相等情况
                int[] equalNum11=equalNum(nums11);
                int[] equalNum22=equalNum(nums22);
                System.out.println("三张牌的相等情况--数组A:"+Arrays.toString(equalNum11));
                System.out.println("三张牌的相等情况--数组B:"+Arrays.toString(equalNum22));
                
                //7.判断输赢
                int whoWin=whoWin(equalNum11, nums11, equalNum22, nums22);
                System.out.println(""+whoWin);
                
            }
            
            //是否继续
            System.out.println("是否继续?输入N或n退出,其他任意键继续!");
            String string = scanner.next();
            string=string.toUpperCase();
            if("N".equals(string)){
                isContinue=false;
            }
        }

    }

    /*1.判断输入的内容是否合法
     *          不合法两种情况:(1)出现的字符不是2,3,4,5,6,7,8,9,10,J,Q,K,A
                                (2)每种牌只有4张,超过4张则不合法了
     *方法说明:
     *该方法只处理情况(1),情况(2)放在判断输赢的时候处理,因为第二种情况涉及牌面转化后计算的问题*/
    public static boolean isValid(String num1, String num2) {
        String reg = "([2-9JQKA]|10){3}";// 正则匹配,只能出现2,3,4,5,6,7,8,9,10,J,Q,K,A,并且一共只能出现3次
        boolean a = num1.matches(reg);
        boolean b = num2.matches(reg);

        // 有一方不合法就返回false
        if (a == false || b == false) {
            return false;
        } else {
            // 都合法
            return true;
        }
    }

    // 1.拆分字符串,得到三个数字
    public static String[] getStrArray(String num) {
        // 字符串的长度和拆分后的数组
        int length = num.length();
        String[] nums = new String[3];
        // 无论输入的J,Q,K,A是否为大写,都改为大写
        num.toUpperCase();

        // 字符串不含10时,长度都为3
        if (length == 3) {
            // nums=num.split("");//使用该方法拆分会多出一个空格位--比如33a-->[,3,3,1]
            for (int i = 0; i  2) {
                nums[0] = nums[2] = "10";
                nums[1] = num.substring(2, 3);
            } else {
                // 两个1距离等于2时,说明两个10是挨在一起的
                if (first == 0) {
                    nums[0] = nums[1] = "10";
                    nums[2] = num.substring(4);
                } else {
                    nums[0] = num.substring(0, 1);
                    nums[1] = nums[2] = "10";
                }
            }

        } else {
            // 字符串为3个10
            for (int i = 0; i  b[1]) {
                return 1;
            } else if (a[1]  primaryB[0]) {
                    return 1;
                } else if (primaryA[0]  b[1]) {
                        return 1;
                    } else if (a[1]  thirdB) {
                            return 1;
                        } else if (thirdA  primaryB[2]) {
                        return 1;
                    } else if (primaryA[2]  primaryB[1]) {
                            return 1;
                        } else if (primaryA[1]  primaryB[0]) {
                                return 1;
                            } else if (primaryA[0] <h2 id="strong-Run-the-test-strong"><strong>Run the test</strong></h2><p><strong>The length is illegal</strong><br><img src="/static/imghw/default1.png" data-src="https://img.php.cn/upload/article/000/000/001/383c341ff337c87b48f4468a5b9909cf-0.png" class="lazy" alt="How to implement the Zha Jinhua game with code"></p><p><strong>A single card 6 appears 5 times, which is illegal</strong><br><img src="/static/imghw/default1.png" data-src="https://img.php.cn/upload/article/000/000/001/112731fc5aabcfefb7340343c06be2b1-1.png" class="lazy" alt="How to implement the Zha Jinhua game with code"></p><p><strong>Leopard</strong><br><img src="/static/imghw/default1.png" data-src="https://img.php.cn/upload/article/000/000/001/112731fc5aabcfefb7340343c06be2b1-2.png" class="lazy" alt="How to implement the Zha Jinhua game with code"></p><p><strong>Shunzi and Pair</strong><br><img src="/static/imghw/default1.png" data-src="https://img.php.cn/upload/article/000/000/001/112731fc5aabcfefb7340343c06be2b1-3.png" class="lazy" alt="How to implement the Zha Jinhua game with code"></p><p><strong> are all letters, and Shunzi and Pair</strong><br><img src="/static/imghw/default1.png" data-src="https://img.php.cn/upload/article/000/000/001/4d65838ea7c1c524e17fdc04439ab32c-4.png" class="lazy" alt="How to implement the Zha Jinhua game with code"></p><p><strong> appears 10, two straights</strong><br><img src="/static/imghw/default1.png" data-src="https://img.php.cn/upload/article/000/000/001/4d65838ea7c1c524e17fdc04439ab32c-5.png" class="lazy" alt="How to implement the Zha Jinhua game with code"></p><p><strong> have no card type, directly compare the big and small</strong> <br><img src="/static/imghw/default1.png" data-src="https://img.php.cn/upload/article/000/000/001/4d65838ea7c1c524e17fdc04439ab32c-6.png" class="lazy" alt="How to implement the Zha Jinhua game with code"></p>
Copy after login

The above is the detailed content of How to implement the Zha Jinhua game with code. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

CLIP-BEVFormer: Explicitly supervise the BEVFormer structure to improve long-tail detection performance CLIP-BEVFormer: Explicitly supervise the BEVFormer structure to improve long-tail detection performance Mar 26, 2024 pm 12:41 PM

Written above &amp; the author’s personal understanding: At present, in the entire autonomous driving system, the perception module plays a vital role. The autonomous vehicle driving on the road can only obtain accurate perception results through the perception module. The downstream regulation and control module in the autonomous driving system makes timely and correct judgments and behavioral decisions. Currently, cars with autonomous driving functions are usually equipped with a variety of data information sensors including surround-view camera sensors, lidar sensors, and millimeter-wave radar sensors to collect information in different modalities to achieve accurate perception tasks. The BEV perception algorithm based on pure vision is favored by the industry because of its low hardware cost and easy deployment, and its output results can be easily applied to various downstream tasks.

Implementing Machine Learning Algorithms in C++: Common Challenges and Solutions Implementing Machine Learning Algorithms in C++: Common Challenges and Solutions Jun 03, 2024 pm 01:25 PM

Common challenges faced by machine learning algorithms in C++ include memory management, multi-threading, performance optimization, and maintainability. Solutions include using smart pointers, modern threading libraries, SIMD instructions and third-party libraries, as well as following coding style guidelines and using automation tools. Practical cases show how to use the Eigen library to implement linear regression algorithms, effectively manage memory and use high-performance matrix operations.

Explore the underlying principles and algorithm selection of the C++sort function Explore the underlying principles and algorithm selection of the C++sort function Apr 02, 2024 pm 05:36 PM

The bottom layer of the C++sort function uses merge sort, its complexity is O(nlogn), and provides different sorting algorithm choices, including quick sort, heap sort and stable sort.

Improved detection algorithm: for target detection in high-resolution optical remote sensing images Improved detection algorithm: for target detection in high-resolution optical remote sensing images Jun 06, 2024 pm 12:33 PM

01 Outlook Summary Currently, it is difficult to achieve an appropriate balance between detection efficiency and detection results. We have developed an enhanced YOLOv5 algorithm for target detection in high-resolution optical remote sensing images, using multi-layer feature pyramids, multi-detection head strategies and hybrid attention modules to improve the effect of the target detection network in optical remote sensing images. According to the SIMD data set, the mAP of the new algorithm is 2.2% better than YOLOv5 and 8.48% better than YOLOX, achieving a better balance between detection results and speed. 02 Background & Motivation With the rapid development of remote sensing technology, high-resolution optical remote sensing images have been used to describe many objects on the earth’s surface, including aircraft, cars, buildings, etc. Object detection in the interpretation of remote sensing images

Can artificial intelligence predict crime? Explore CrimeGPT's capabilities Can artificial intelligence predict crime? Explore CrimeGPT's capabilities Mar 22, 2024 pm 10:10 PM

The convergence of artificial intelligence (AI) and law enforcement opens up new possibilities for crime prevention and detection. The predictive capabilities of artificial intelligence are widely used in systems such as CrimeGPT (Crime Prediction Technology) to predict criminal activities. This article explores the potential of artificial intelligence in crime prediction, its current applications, the challenges it faces, and the possible ethical implications of the technology. Artificial Intelligence and Crime Prediction: The Basics CrimeGPT uses machine learning algorithms to analyze large data sets, identifying patterns that can predict where and when crimes are likely to occur. These data sets include historical crime statistics, demographic information, economic indicators, weather patterns, and more. By identifying trends that human analysts might miss, artificial intelligence can empower law enforcement agencies

Application of algorithms in the construction of 58 portrait platform Application of algorithms in the construction of 58 portrait platform May 09, 2024 am 09:01 AM

1. Background of the Construction of 58 Portraits Platform First of all, I would like to share with you the background of the construction of the 58 Portrait Platform. 1. The traditional thinking of the traditional profiling platform is no longer enough. Building a user profiling platform relies on data warehouse modeling capabilities to integrate data from multiple business lines to build accurate user portraits; it also requires data mining to understand user behavior, interests and needs, and provide algorithms. side capabilities; finally, it also needs to have data platform capabilities to efficiently store, query and share user profile data and provide profile services. The main difference between a self-built business profiling platform and a middle-office profiling platform is that the self-built profiling platform serves a single business line and can be customized on demand; the mid-office platform serves multiple business lines, has complex modeling, and provides more general capabilities. 2.58 User portraits of the background of Zhongtai portrait construction

Selected Java JPA interview questions: Test your mastery of the persistence framework Selected Java JPA interview questions: Test your mastery of the persistence framework Feb 19, 2024 pm 09:12 PM

What is JPA? How is it different from JDBC? JPA (JavaPersistence API) is a standard interface for object-relational mapping (ORM), which allows Java developers to use familiar Java objects to operate databases without writing SQL queries directly against the database. JDBC (JavaDatabaseConnectivity) is Java's standard API for connecting to databases. It requires developers to use SQL statements to operate the database. JPA encapsulates JDBC, provides a more convenient and higher-level API for object-relational mapping, and simplifies data access operations. In JPA, what is an entity? entity

PHP algorithm analysis: efficient method to find missing numbers in an array PHP algorithm analysis: efficient method to find missing numbers in an array Mar 02, 2024 am 08:39 AM

PHP algorithm analysis: An efficient method to find missing numbers in an array. In the process of developing PHP applications, we often encounter situations where we need to find missing numbers in an array. This situation is very common in data processing and algorithm design, so we need to master efficient search algorithms to solve this problem. This article will introduce an efficient method to find missing numbers in an array, and attach specific PHP code examples. Problem Description Suppose we have an array containing integers between 1 and 100, but one number is missing. We need to design a

See all articles