1. 程式人生 > >java實現撲克牌中的順子匹配的正則實現

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("順子");
            }
    }
}