【Java】从扑克牌中随机抽5张牌,判断是不是一个顺子

  • 从扑克牌中随机抽5张牌,判断是不是一个顺子,即这5张牌是不是连续的。且大小王能够当做任意一张牌。(2不算入顺子)
package com.zzz.demo;

import java.util.*;
import java.util.Map.Entry;

/**
 * 从扑克牌中随机抽5张牌,判断是不是一个顺子,即这5张牌是不是连续的。且大小王能够当做任意一张牌。(2不算入顺子)
 */
public class ShunZi {
	
	static int count = 5;//抽的张数
	
	static final List<String> HUASE = Arrays.asList("黑桃","梅花","红心","方块");
	static final List<String> NUM_PAI = Arrays.asList("3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A", "2");
	static final List<String> WANG = Arrays.asList("大王", "小王");
	static final List<String> WHOLE_PAI = new ArrayList<String>();//54张牌
	
	static {
		HUASE.forEach(x->setHuase(x));
		WHOLE_PAI.addAll(WANG);
	}
	
	public static void main(String[] args) {
		
		/**
		
			Map<Integer, String> pai = getPai();
			boolean yn = getShunZi(pai);
		
		 */
		
		long startTime = System.nanoTime();
		Map<Integer, String> pai = null;
		boolean yn = false;
		int num = 0;
		while(yn == false) {
			pai = getPai();
			++num;
			yn = getShunZi(pai);
		}
		if(yn) {
			System.out.println(String.format("第 %s 次出现顺子,这 %s 张牌分别是:", num, count));
			for(Entry<Integer, String> entry : pai.entrySet()) {
				System.out.print(entry.getValue() + "\t");
			}
		}
		System.out.println("\n" + String.format("共耗时: %s秒", (double)((System.nanoTime() - startTime))/ 1_000_000_000));
	}
	
	/**
	 * 判断抽出的牌是否为顺子
	 * @param pai
	 * @return
	 */
	public static boolean getShunZi(Map<Integer, String> pai) {
		int spec = 0, maxIndex = 0, minIndex = 0, two = 0;
		boolean is = true;
		List<Integer> indexs = new ArrayList<Integer>();
		for(Entry<Integer, String> entry : pai.entrySet()) {
			String value = entry.getValue();
			if(value.length() == 2) {//大小王的数量
				++spec;
			}else{
				String num = value.replace(value.subSequence(0, 2).toString(), "");
				if(num.equals("2")) {//牌为2的数量
					++two;
				}else {
					indexs.add(NUM_PAI.indexOf(num));
				}
			}
		}
		maxIndex = Collections.max(indexs);
		minIndex = Collections.min(indexs);
		int size = new HashSet<>(indexs).size();
		if((two > 0) || (maxIndex - minIndex > (count-1)) || (indexs.size() - size != spec) || (size + spec != count)) {
			is = false;
		}
		return is;
	}
	
	/**
	 * 随机获取牌
	 * @return
	 */
	public static Map<Integer, String> getPai() {
		Map<Integer, String> map = new HashMap<Integer, String>();
		Random random = new Random();
		while (map.size() < count) {
			int nextInt = random.nextInt(WHOLE_PAI.size());
			map.put(nextInt, WHOLE_PAI.get(nextInt));
		}
		return map;
	}
	
	public static void setHuase(String huase) {
		NUM_PAI.forEach(x->addPai(huase, x));
	}
	
	public static void addPai(String huase, String num) {
		WHOLE_PAI.add(huase + num);
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值