模拟扑克牌,随机抽取五张牌,判断是否为同花顺
·
今天去面试,遇到这个面试题,当时想法想通了,我跟面试官说给我半小时,但是超时了没写出来。
回来复盘一下~
思路步骤:
①创建map容器存储扑克牌key为牌的索引,value为牌的值
②按照同花顺顺序存储到容器
③在52张牌内随机抽取五个索引
④索引排序
⑤判断索引是否连续和花色是否统一
实现代码:
/**
* @Date 2022/8/19 10:12
* @Author PAMELA
* @Description 模拟扑克牌,随机抽取五张牌,判断是否为同花顺
*/
public class Poker {
public static void main(String[] args) {
//创建扑克容器 key为索引 value为值
Map<Integer,String> hashMap = new HashMap<Integer,String>();
//创建花色 与 值
String[] colors = {"♦","♥","♠","♣"};
String[] numbers = {"2","3","4","5","6","7","8","9","10","J","Q","K","A"};
//组成牌 存入容器
int index=0;
for(String color : colors){
for (String number : numbers) {
hashMap.put(index,color+number);
index++;
}
}
System.out.println(hashMap);
//是否同花顺
boolean flag = true;
//随机的5个索引
int[] randIndex = new int[5];
Random random = new Random();
List<String> five = new ArrayList<String>();
//随机抽选5张牌
for (int i=0;i<5;i++){
//保存索引
randIndex[i] = random.nextInt(index);
//保存数据
five.add(hashMap.get(randIndex[i])) ;
}
//====================================测试同花顺数据===============================
/* //对应牌的索引
randIndex[0]=20;
randIndex[1]=21;
randIndex[2]=22;
randIndex[3]=23;
randIndex[4]=24;
//对应索引的值
five.set(0,"♥9");
five.set(1,"♥10");
five.set(2,"♥J");
five.set(3,"♥Q");
five.set(4,"♥K");*/
//==============================================================================
//索引排序
Arrays.sort(randIndex);
for (int i = 0; i < 5; i++) {
System.out.print(randIndex[i]+" ");
}
System.out.println();
//取头一张牌的花色
String s = five.get(0);
char color = s.charAt(0);
for (int i = 0; i < 4; i++) {
//比较剩余牌的花色
String s1 = hashMap.get(randIndex[i]);
char c = s1.charAt(0);
if (randIndex[i]+1==randIndex[i+1] && c==color){
continue;
}else {
flag=false;
break;
}
}
System.out.println(five);
if (flag) {
System.out.println("您的牌是同花顺!");
}else{
System.out.println("您的牌不是同花顺!");
}
}
}
测试结果:
{0=♦2, 1=♦3, 2=♦4, 3=♦5, 4=♦6, 5=♦7, 6=♦8, 7=♦9, 8=♦10, 9=♦J, 10=♦Q, 11=♦K, 12=♦A, 13=♥2, 14=♥3, 15=♥4, 16=♥5, 17=♥6, 18=♥7, 19=♥8, 20=♥9, 21=♥10, 22=♥J, 23=♥Q, 24=♥K, 25=♥A, 26=♠2, 27=♠3, 28=♠4, 29=♠5, 30=♠6, 31=♠7, 32=♠8, 33=♠9, 34=♠10, 35=♠J, 36=♠Q, 37=♠K, 38=♠A, 39=♣2, 40=♣3, 41=♣4, 42=♣5, 43=♣6, 44=♣7, 45=♣8, 46=♣9, 47=♣10, 48=♣J, 49=♣Q, 50=♣K, 51=♣A}
9 17 25 35 36
[♠J, ♦J, ♥6, ♥A, ♠Q]
您的牌不是同花顺!
更多推荐




所有评论(0)