java实现扑克牌中的顺子匹配的正则实现

从扑克牌中随机抽5张排,判断是不是一个顺子,即这5张牌是不是连续的。2~10为数字本身,A为1,J为11,Q为12,K为13,而大,小王可以看成任意数字。

普通解法毫无乐趣于是我就想这道题是不是能用正则匹配,写是写出来了但是效率好像不太高···

import java.util.Arrays;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main {
    public static void main(String[] args) {
        int[] puke = {101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113,//有个坑00开头代表八进制数
                201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213,
                301, 302, 303, 304, 305, 306, 307, 308, 309, 310, 311, 312, 313,
                401, 402, 403, 404, 405, 406, 407, 408, 409, 410, 411, 412, 413,
                500, 600//分别表示大小王
        };//扑克牌生成完毕
       StringBuffer sb = new StringBuffer("");  //做一个字符串把随机生成的扑克牌放进去
            while (sb.length()<15) {//抽5张牌
                int card = puke[(int) (Math.random() * 54)];
                if (Pattern.compile("(?=(?:\\d{3})*)" + String.valueOf(card)).matcher(sb).find()) {
                    continue; //如果加载过了就放弃这一张,110102中101不是我想匹配的必须剔除
                } else {
                    sb.append(card);
                }
            }
            System.out.println(sb);
            //放到1个int数组并排序
            Matcher matcher = Pattern.compile("\\d{3}").matcher(sb);
            int[] arr = new int[5];
            int i = 0;
            while (matcher.find()) {
                arr[i++] = Integer.parseInt(matcher.group()) % 100;//把除100的余数赋值
            }
            Arrays.sort(arr);
            System.out.println(Arrays.toString(arr));
            int count = 0; //统计万能牌个数
            for (i = 0; i < 4; i++) {
                if (arr[i] == 0) {
                    count++;
                } else {
                    if (arr[i] == arr[i + 1]) {
                        count = count - 100;//重复了肯定不是随便瞎写一个肯定不行的式子
                    }
                   else {
                        count += arr[i]+1-arr[i+1];
                    }
                }
            }
            if (count < 0) {
                 System.out.println("不是顺子");
            } else {
                System.out.println("顺子");
            }
    }
}

猜你喜欢

转载自blog.csdn.net/qq_43313769/article/details/85491663