我们平时玩斗地主的时候,需要把一副扑克牌打乱顺序,发给玩家,在生活中我们如果洗一次牌和洗一百次牌乱序的效果是不同的,那么我们怎么利用计算机程序模拟洗牌的动作呢。
package com.test1;
public class H3 {
public static void show(String[] x){
for (int i = 0; i <x.length ; i++) {
System.out.print(x[i]+" ");
}
System.out.println();
}
public static void main(String[] args) {
String[] x={"3","4","5","6","7","8","9","10","J","Q","K","A","2","小王","大王"};
show(x);
//洗牌
for(int i=0;i<9999;i++){//洗牌次数。大家可以尝试洗1次和洗9999次乱序的情况。
int m=(int)(Math.random()*x.length);
int n=(int)(Math.random()*x.length);
String t=x[m];
x[m]=x[n];
x[n]=t;
}
show(x);
}
}
运行结果如下
3 4 5 6 7 8 9 10 J Q K A 2 小王 大王
5 3 8 A 小王 2 4 6 9 10 7 大王 J Q K