重新整理数组的打乱算法,每次产生两个随机数,将产生的两个数对应索引位置的元素位置对换,这样重复1000次,达到随机的目的。若要使结果更准确,则可多次调用该方法进行打乱。
package jim.random;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
/**
* 随机洗54张牌
* */
public class RandomPocker {
/** 牌的花色 */
static Map<Integer,String> types = new HashMap<Integer,String>();
/***/
static Map<Integer,Card> cardMap = new HashMap<Integer,Card>();
static {
types.put(0, "红桃");
types.put(1, "黑桃");
types.put(2, "方片");
types.put(3, "梅花");
for(int i = 1; i < 14; i ++){
// 花色
for(int j = 0; j < 4; j ++){
Card card = new Card(String.valueOf(i),types.get(j));
cardMap.put((i-1)*4+j, card);
}
}
cardMap.put(52,new Card("0","大王"));
cardMap.put(53,new Card("0","小 王"));
}
public static void main(String[] args) {
List<Card> cards = new ArrayList<Card>(cardMap.values());
random(cards);
// for(int i = 0; i < cards.size(); i ++){
// System.out.println(cards.get(i).getNum()+"-"+cards.get(i).getType());
// }
}
/**
* 循环1000次,每次随机两个数,取对应位置的对象交换位置。
* */
public static <T> void random(List<T> rd){
int size = rd.size();
for (int i = 0; i < 1000; i ++){
Random random = new Random();
int ran1 = random.nextInt(size);
int ran2 = random.nextInt(size);
if (ran1 == ran2){
continue;
}
T tmp = rd.get(ran1);
rd.set(ran1, rd.get(ran2));
rd.set(ran2, tmp);
}
}
/**
* 扑克类
* */
public static class Card{
/**
* 点数
* */
private String num;
/**
* 花色
* */
private String type;
public Card(String num, String type) {
super();
this.num = num;
this.type = type;
}
public String getNum() {
return num;
}
public void setNum(String num) {
this.num = num;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
}
}