洗牌的功能引入了Map集合,不然的话需要对花色定义大小,还要对牌的字数定义大小,因为JQK肯定和数字要比较,所以这样很麻烦而且我也不会,所以引入Map,用编号按照花色和字数进行全排序,也就是按照大小顺序全部放进Map中,以编号为key,以牌为Value,代码如下
package com.interview.test.com.interview.test.hashtest; import java.util.*; public class HashTest { public static void main(String[] args) { //定义花色 ArrayList<String> flowers = new ArrayList<>(); //定义数字 ArrayList<String> nums = new ArrayList<>(); //定义组合牌池 ArrayList<String> cardPool = new ArrayList<>(); //统一添加 Collections.addAll(flowers,"♠","♥","♣","♦"); Collections.addAll(nums,"A","2","3","4","5","6","7","8","9","10","J","Q","K"); //先往牌池里面组合添加 for(String flower : flowers){ for(String num : nums){ cardPool.add(flower+num); } } //真正的Map牌堆 Map<Integer,String> map = new HashMap<>(); Integer count = 0; map.put(++count,"JOKER"); map.put(++count,"joker"); for(String s : cardPool){ map.put(++count,s); } //获取key值集合,打乱排序,分给三个用户 Set<Integer> keys = map.keySet(); //因为打乱排序这个方法shuffle只能传List集合,所以要把set变成list ArrayList<Integer> keysList = new ArrayList<>(); keysList.addAll(keys); //先定义三个用户的牌和底牌编号集合,再进行打乱排序分发 ArrayList<Integer> gamer1Nums = new ArrayList<>(); ArrayList<Integer> gamer2Nums = new ArrayList<>(); ArrayList<Integer> gamer3Nums = new ArrayList<>(); ArrayList<Integer> lastCardsNums = new ArrayList<>(); Collections.shuffle(keysList); //进行分发 for(int i = 0;i < keysList.size();i++){ if(i>50){ lastCardsNums.add(keysList.get(i)); } else if(i%3==0){ gamer1Nums.add(keysList.get(i)); }else if(i%3==1){ gamer2Nums.add(keysList.get(i)); }else if(i%3==2){ gamer3Nums.add(keysList.get(i)); } } //给三个人的牌编号进行排序 Collections.sort(gamer1Nums); Collections.sort(gamer2Nums); Collections.sort(gamer3Nums); //创建三个人和底牌的牌集合 ArrayList<String> gamer1Cards = new ArrayList<>(); ArrayList<String> gamer2Cards = new ArrayList<>(); ArrayList<String> gamer3Cards = new ArrayList<>(); ArrayList<String> lastCards = new ArrayList<>(); //根据序号发牌 for(Integer i : gamer1Nums){ gamer1Cards.add(map.get(i)); } for(Integer i : gamer2Nums){ gamer2Cards.add(map.get(i)); } for(Integer i : gamer3Nums){ gamer3Cards.add(map.get(i)); } for(Integer i : lastCardsNums){ lastCards.add(map.get(i)); } System.out.println(gamer1Cards); System.out.println(gamer2Cards); System.out.println(gamer3Cards); System.out.println(lastCards); } }