打扑克使用52张牌(大小王不算),由整齐的顺序随机洗到混乱的状态
package laojiu;
/**
* 模拟实现洗牌的过程
* @author QJ
*@date 2020.7.9 晚上
*/
public class ShuffleCardsDome {
public static void main(String[] args) {
final int N = 52; //52张牌
int[] cards = new int[N];
//牌的花色数组
String[] cardColors = {"黑桃","红心","方块","梅花"};
//牌面数组
String[] cardValues = {
"A","2","3","4","5","6","7","8","9","10",
"J","Q","k"};
for(int i = 0;i < cards.length;i++) {
cards[i]=i; //牌面与变量的值一致,0-51之间
}
System.out.println("洗牌前:");
// for ( i = 0; i < cards.length; i++) { 用“//”的代码,由数字演变成牌面数字 花色的过程
// System.out.print(cards[i]);
// if((i+1) % 13 == 0) {
// System.out.println();
// }else {
// System.out.print(",");
// }
// }
for (int i = 0; i < cards.length; i++) {
//System.out.print(cards[i]);
System.out.printf("%s-%s",cardColors[cards[i] / 13],cardValues[cards[i]%13]);
if((i+1) % 13 == 0) {
System.out.println();
}else {
System.out.print("\t");
}
}
//洗牌:随机生成一个0-51之间的数字newIndex,cards[i]和cards[newIndex]元素相交换
for(int i=0;i<cards.length;i++) {
int newIndex = (int)(Math.random()*N); //0-51之间的随机数字
int temp = cards[i];
cards[i] = cards[newIndex];
cards[newIndex] = temp;
}
// //牌的花色数组
// String[] cardColors = {"黑桃","红心","方块","梅花"};
// //牌面数组
// String[] cardValues = {
// "A","2","3","4","5","6","7","8","9","10",
// "J","Q","k"};
//
System.out.println("洗牌后:");
for (int i = 0; i < cards.length; i++) {
//System.out.print(cards[i]);
System.out.printf("%s-%s",cardColors[cards[i] / 13],cardValues[cards[i]%13]);
//cardColors[cards[i] / 13]结果只可能为:0[黑桃],1[红心],2[方块],3[梅花]
//cardValues[card[i]%13]的结果可能为0,1,2,3,......11,12,13 分别代表A,2,3,4.....J,Q,K
if((i+1) % 13 == 0) {
System.out.println();
}else {
System.out.print("\t");
}
}
}
}
上面代码的控制台:

