Java集合-单例模式斗地主&Collections类的shuffle方法了解

摘要:
1/1组合卡片2//定义一组卡片3ArrayList<String>poker=newArrayList<String>();4//定义装饰5String[]colors={“”,“”,”,“,”};6//定义序列号7String[]数字={“3”、“4”、“5”、“6”、“7”、“8”、“9”、“10”、“J”、“Q”、“K”、“A”、“2”};8//定义size king 9String[]joker=newString[]{“Big king”,“Little king”};10//组合卡11用于{12用于{13扑克。添加;14}15}16扑克。添加17poker.add;18/*System.out.println;//打桩测试*/使用Collections工具类的静态方法publicstaticvoidshuffle进行洗牌(List

在学完Collection接口,以及其下面的List接口,了解几种基本的集合实现类如ArrayList、LinkedList和Vector后,可以做一个简单的斗地主,这里记录一下使用ArrayList来模拟实现斗地主的组合牌洗牌发牌看牌动作。

案例分析

1. 组装54张扑克牌
2. 将54张牌顺序打乱
3. 三个玩家参与游戏,三人交替摸牌,每人17张牌,最后三张留作底牌。
4. 查看三人各自手中的牌(按照牌的大小排序)、底牌

组合牌

使用集合,循环遍历完成。

 1         //1 组合牌
 2         //定义一个集合保存一副牌
 3         ArrayList<String> poker=new ArrayList<String>();
 4         //定义花色
 5         String[] colors={"♠","♦","♣","♥"};
 6         //定义序号
 7         String[] numbers={"3","4","5","6","7","8","9","10","J","Q","K","A","2"};
 8         //定义大小王
 9         String[] joker=new String[]{"大王","小王"};
10         //组合牌
11         for (String color : colors) {
12             for (String number : numbers) {
13                 poker.add(color+number);
14             }
15         }
16         poker.add(joker[0]);
17         poker.add(joker[1]);
18         /*System.out.println(poker);//打桩测试*/

洗牌

使用Collections工具类的静态方法 public static void shuffle(List<?> list)完成。

1         //2 洗牌
2         Collections.shuffle(poker);
3         /*System.out.println(poker);*/

查看shuffle源码,发现底层调用了shuffle(list,rnd)方法,其中list为传入的集合,rnd为一个Random随机数类。另外Random是一个线程安全的类,在高并发情况下可能会导致性能下降,如果需要考虑高并发可以使用ThreadLocalRandom,如果是密码相关的应用使用SecureRandom。

1     public static void shuffle(List<?> list) {
2         Random rnd = r;
3         if (rnd == null)
4             r = rnd = new Random(); // harmless race.
5         shuffle(list, rnd);
6     }

继续查看shuffle方法,发现有两种情况,一种是list集合的大小小于5,或者list集合属于RandomAccess实例时执行swap方法,另外一种情况是先将list转换成一个数组,然后对数组进行随机交换。前一种情况是针对底层是数组的集合,如ArrayList,后面一种情况是针对底层是链表实现的集合,如LinkedList,两种选择只是选择更优的算法,让执行更快。

 1     public static void shuffle(List<?> list, Random rnd) {
 2         int size = list.size();
 3         if (size < SHUFFLE_THRESHOLD || list instanceof RandomAccess) {
 4             for (int i=size; i>1; i--)
 5                 swap(list, i-1, rnd.nextInt(i));
 6         } else {
 7             Object arr[] = list.toArray();
 8 
 9             // Shuffle array
10             for (int i=size; i>1; i--)
11                 swap(arr, i-1, rnd.nextInt(i));
12 
13             // Dump array back into list
14             // instead of using a raw type here, it's possible to capture
15             // the wildcard but it will require a call to a supplementary
16             // private method
17             ListIterator it = list.listIterator();
18             for (int i=0; i<arr.length; i++) {
19                 it.next();
20                 it.set(arr[i]);
21             }
22         }
23     }

查看底层是数组的swap方法,以及for循环,发现先从数组最后一个元素开始比较,逐一往前面移动下标,直到第二个元素才停止交换。交换的就是当前位置的元素和当前位置之前的随机位置的元素,这点从rnd.nextInt(i)能够看出来。

1     public static void swap(List<?> list, int i, int j) {
2         // instead of using a raw type here, it's possible to capture
3         // the wildcard but it will require a call to a supplementary
4         // private method
5         final List l = list;
6         l.set(i, l.set(j, l.get(i)));
7     }

查看底层是链表的swap方法,就是交换相互位置的元素,交换情况跟上面类似,也是交换当前位置元素和当前位置之前随机位置的元素。

1     private static void swap(Object[] arr, int i, int j) {
2         Object tmp = arr[i];
3         arr[i] = arr[j];
4         arr[j] = tmp;
5     }

发牌

发牌需要创建4个容器接收牌。

 1         //3 发牌,ArrayList底层是一个数组,根据索引来发牌
 2         //定义三个集合,用于储存发的牌
 3         ArrayList<String> player1=new ArrayList<String>();
 4         ArrayList<String> player2=new ArrayList<String>();
 5         ArrayList<String> player3=new ArrayList<String>();
 6         ArrayList<String> leftPoker=new ArrayList<String>();//底牌
 7         //发牌
 8         for (int i = 0; i < poker.size(); i++) {
 9             //当索引为51时开始,不再发牌,留作底牌,其他发掉
10             if(i>=51){
11                 leftPoker.add(poker.get(i));
12             }else if(i%3==0){
13                 player1.add(poker.get(i));
14             }else if(i%3==1){
15                 player2.add(poker.get(i));
16             }else if(i%3==2){
17                 player3.add(poker.get(i));
18             }
19         }

看牌

看牌就是打印集合中的内容。

1         //4 看牌
2         System.out.println("赌王的牌:"+player1);
3         System.out.println("赌圣的牌:"+player2);
4         System.out.println("赌仙的牌:"+player3);
5         System.out.println("底牌"+leftPoker);

完整代码

Java集合-单例模式斗地主&amp;amp;Collections类的shuffle方法了解第1张View Code

控制台打印结果

Java集合-单例模式斗地主&amp;amp;Collections类的shuffle方法了解第2张

Java集合-单例模式斗地主&amp;amp;Collections类的shuffle方法了解第3张

以上实现了一个简单的模拟斗地主发牌动作,加深对集合的理解。

参考博客:

https://blog.csdn.net/weixin_38237873/article/details/83003422

免责声明:文章转载自《Java集合-单例模式斗地主&amp;amp;Collections类的shuffle方法了解》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇大话数据结构之一(绪论、算法)windows添加右键菜单下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

相关文章

接口调用帮助类(http调接口、WebService动态调接口)

1.HttpGetPost调用接口实现 1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Net; 6 using System.IO; 7 8 namespace He...

C#温故而知新学习系列之XML编程—XmlSerializer类把对象序列化为XML文档(五)

  前言    在XMLSerializer类中,包含了把对象序列化为XML文档和把XML文档反序列化为对象的方法,在创建一个类时,只要在该类的属性上加上自定义属性,XMLSerializer就可以读取这些属性,就可以将它们映射成XML元素和属性了   在XMLSerializer类中,把对象序列化为XML文档用Serialize()方法实现,反序列化通过...

C# 文件操作封装类(删除,移动,复制,重命名)

最近发现群共享里面有个C# 文件操作封装类,其方法是调用Windows API 来操作的文件的删除、移动、复制、重命名操作。下载下来一试,发现果然不错,特在此记录,以防丢失! 文件操作类代码如下: C# 文件操作类using System; using System.Runtime.InteropServices; using System.IO;...

VB.Net Socket实现Http文件上传及下载类

GET访问: dim httpClient as new WebClient() httpClient.strUrl="http://www.baidu/com?wd=hello" httpClient.Proc() Msgbox(httpClient.RespHtml) POST访问: dim httpClient as new WebClient()...

从源码中学习设计模式系列——单例模式序/反序列化以及反射攻击的问题(二)

一、前言 这篇文章是学习单例模式的第二篇,之前的文章一下子就给出来看起来很高大上的实现方法,但是这种模式还是存在漏洞的,具体有什么问题,大家可以停顿一会儿,思考一下。好了,不卖关子了,下面我们来看看每种单例模式存在的问题以及解决办法。 二、每种Singleton 模式的演进 模式一 public classLazySingleton {...

numpy随机索引(不重复)和打乱元素

def getRandomIndex(n, x): # 索引范围为[0, n),随机选x个不重复,注意replace=False才是不重复,replace=True则有可能重复 index = np.random.choice(np.arange(n), size=x, replace=False) return index getRa...