zoukankan      html  css  js  c++  java
  • 数组随机排序

    以前没怎么用过,下面简单看一看Random是怎么用的。 假如被问到如何利用对一个数组进行shuffle,那么我们可以有一些简单的方法。

    1. 使用系统自带的sort,然后传入一个Comparator,里面带一个double r = Math.random(),代码如下

    这个Time Complexity就是O(nlogn)了

        Integer[] nums = new Integer[] {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
            
            
            Arrays.sort(nums, new Comparator<Integer>() {
                public int compare(Integer num1, Integer num2) {
                    double r = Math.random();
                    if (r < 0.5) {
                        return -1;
                    } else if (r > 0.5) {
                        return 1;
                    } else {
                        return 0;
                    }
                }
            });
            

    2. 使用Knuth Shuffle,也是系统的random,不过是java.util.Random类。

    Time Complexity O(n)

    Random random = new Random(System.currentTimeMillis());
            
            for (int i = 0; i < nums.length; i++) {
                int r = random.nextInt(i + 1);
                swap(nums, i, r);
            }
            
            
            for (Integer i : nums) {
                System.out.print(i + "");
            }

    以上是用系统生成的随机数,那如果要自己生成, 还需要好好研究Random Generator。

    常用的生成伪随机数的算法有linear congruential generator等。主要公式如下

    Xn+1 = (a * Xn + c) mod m,  在Java里,  m = 2 ^ 48,   a = 25214903917,  c = 11。  不知道为什么这么设置,但先记下来了

    - https://en.wikipedia.org/wiki/Linear_congruential_generator 

    X_{n+1} = left( a X_n + c 
    ight)~~mod~~m
    where X is the sequence of pseudorandom values, and
    
     m,\, 0<m  – the "modulus"
     a,\,0 < a < m – the "multiplier"
     c,\,0 le c < m – the "increment"
     X_0,\,0 le X_0 < m – the "seed" or "start value"

    https://en.wikipedia.org/wiki/Random_number_generation 

    https://en.wikipedia.org/wiki/Linear_congruential_generator

  • 相关阅读:
    pytorch报错:AttributeError: 'module' object has no attribute '_rebuild_tensor_v2'
    python运行报错:cannot import name 'InteractiveConsole'
    sudo pip3找不到命令
    pytorch入门1——简单的网络搭建
    caffe训练时报错
    python滴啊用caffe时的小坑
    求两个字符串的编辑距离
    归并排序
    复杂度n求数组的第K大值
    牛顿法与拟牛顿法学习笔记(一)牛顿法
  • 原文地址:https://www.cnblogs.com/yrbbest/p/5186837.html
Copyright © 2011-2022 走看看