java洗牌_使用java实现洗牌

static String[] pokers = new String[54];

public static void randomSet(int min, int max, int n, HashSet set) {

if (n > (max - min + 1) || max < min) {

return;

}

for (int i = 0; i < n; i++) {

// 调用Math.random()方法

int num = (int) (Math.random() * (max - min)) + min;

set.add(num);// 将不同的数存入HashSet中

}

int setSize = set.size();

// 如果存入的数小于指定生成的个数,则调用递归再生成剩余个数的随机数,如此循环,直到达到指定大小

if (setSize < n) {

randomSet(min, max, n - setSize, set);// 递归

}

}

public static void main(String []args)throws Exception{

//1.定义花色数组

String[] colors = {"红桃","黑桃","梅花","方片"};

//2.定义牌面数组

String[] numbers = {"A","2","3","4","5","6","7","8","9","10","J","Q","K"};

//3.定义王

String[] kings = {"大王","小王"};

//4.使用循环将牌存储到pokers数组

int index = 0;

for(int i = 0 ; i < numbers.length ; i ++) {

for(int j = 0 ; j < colors.length ; j ++) {

pokers[index ++] = colors[j] + numbers[i];

}

}

//将大小王加入扑克数组

System.arraycopy(kings, 0, pokers, index, 2);

HashSet set = new HashSet();

randomSet(0,100000,54,set);

for (int j : set) {

}

Listlist = new ArrayList<>();

for (Integer str : set) {

list.add(str);

}

Mapmap = new TreeMap<>();

//循环遍历扑克数组,将这个扑克的牌加入map,生成随机数让他们顺序不一样

for(int i = 0 ;i

map.put(list.get(i)+"", pokers[i]);

}

Map resultMap = MapSortDemo.sortMapByKey(map); //按Key进行排序

for (Map.Entry entry : resultMap.entrySet()) {

System.out.println( entry.getValue());

}

/**

* 使用 Map按key进行排序

* @param map

* @return

*/

public static Map sortMapByKey(Map map) {

if (map == null || map.isEmpty()) {

return null;

}

Map sortMap = new TreeMap(

new MapKeyComparator());

sortMap.putAll(map);

return sortMap;

}

}

class MapKeyComparator implements Comparator{

@Override

public int compare(String str1, String str2) {

return str1.compareTo(str2);

}

}

后来发现貌似还有一种更简单的方法,直接使用collections的shuffle方法 打乱list集合里面的数据 就可以了 但是没有经过测试

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值