- 从扑克牌中随机抽5张牌,判断是不是一个顺子,即这5张牌是不是连续的。且大小王能够当做任意一张牌。(2不算入顺子)
package com.zzz.demo;
import java.util.*;
import java.util.Map.Entry;
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>();
static {
HUASE.forEach(x->setHuase(x));
WHOLE_PAI.addAll(WANG);
}
public static void main(String[] args) {
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));
}
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")) {
++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;
}
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);
}
}