• 使用java实现洗牌


    static String[] pokers = new String[54];
    public static void randomSet(int min, int max, int n, HashSet<Integer> 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<Integer> set = new HashSet<Integer>();
    randomSet(0,100000,54,set);
    for (int j : set) {
    }
    List<Integer>list = new ArrayList<>();
    for (Integer str : set) {
    list.add(str);
    }
    Map<String, String>map = new TreeMap<>();
    //循环遍历扑克数组,将这个扑克的牌加入map,生成随机数让他们顺序不一样
    for(int i = 0 ;i<pokers.length;i++){
    map.put(list.get(i)+"", pokers[i]);
    }

    Map<String, String> resultMap = MapSortDemo.sortMapByKey(map); //按Key进行排序
    for (Map.Entry<String, String> entry : resultMap.entrySet()) {
    System.out.println( entry.getValue());
    }

    /**
    * 使用 Map按key进行排序
    * @param map
    * @return
    */
    public static Map<String, String> sortMapByKey(Map<String, String> map) {
    if (map == null || map.isEmpty()) {
    return null;
    }

    Map<String, String> sortMap = new TreeMap<String, String>(
    new MapKeyComparator());

    sortMap.putAll(map);

    return sortMap;
    }
    }

    class MapKeyComparator implements Comparator<String>{

    @Override
    public int compare(String str1, String str2) {

    return str1.compareTo(str2);
    }
    }

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

  • 相关阅读:
    12迭代器
    11(2)Vector(向量)
    11(1) LinkList ---链表
    11集合(Collection<E>) Arraylist
    10异常
    乘法计算过程的模拟
    10 Date详解
    详细的OA系统学习
    8 math类
    Java开发中的23种设计模式详解
  • 原文地址:https://www.cnblogs.com/oushiyang/p/7797954.html
Copyright © 2020-2023  润新知