Java偷懒洗牌算法
Posted codingjav
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java偷懒洗牌算法相关的知识,希望对你有一定的参考价值。
public class Card {
private String card;
private String color;
public Card(String card, String color) {
this.card = card;
this.color = color;
}
public String toString()
{
String ss= color+":"+card+" ";
return ss;
}
}
public class DeskOfCard {
Card[] cards;
public void initCard() {
String num[]={"A","2","3","4","5","6","7","8","9","10","J","Q","K"};
String color[]={"方块","梅花","红桃","黑桃"};
cards = new Card[52];
for (int i=0;i<52;i++) {
cards[i] = new Card(num[i%13], color[i/13]);
}
}
public void shufflecard() {
Random random = new Random();
for (int i=0; i<52;i++) {
int j = random.nextInt(52);
Card temp = cards[i];
cards[i] = cards[j];
cards[j] = temp;
}
}
public void dealcard()//发牌
{
for(int i=0;i<52;i++)
{
if(i%4==0) System.out.println("\\n");
System.out.print(cards[i]);
}
}
public static void main(String[] args) {
DeskOfCard desk = new DeskOfCard();
desk.initCard();
print(desk);
System.out.println("\\n\\n洗牌");
desk.shufflecard();
print(desk);
System.out.println("\\n\\n发牌");
desk.dealcard();
}
public static void print(DeskOfCard desk) {
int i = 0;
for (Card card : desk.cards) {
if (i%13 == 0) {
System.out.println();
}
System.out.printf(card.toString());
i++;
}
}
}
以上是关于Java偷懒洗牌算法的主要内容,如果未能解决你的问题,请参考以下文章