数组随机排序
2016-02-12 08:27
393 查看
以前没怎么用过,下面简单看一看Random是怎么用的。 假如被问到如何利用对一个数组进行shuffle,那么我们可以有一些简单的方法。
1. 使用系统自带的sort,然后传入一个Comparator,里面带一个double r = Math.random(),代码如下
这个Time Complexity就是O(nlogn)了
2. 使用Knuth Shuffle,也是系统的random,不过是java.util.Random类。
Time Complexity O(n)
以上是用系统生成的随机数,那如果要自己生成, 还需要好好研究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
https://en.wikipedia.org/wiki/Random_number_generation https://en.wikipedia.org/wiki/Linear_congruential_generator
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 \right)~~\bmod~~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
相关文章推荐
- HDU 5211 Mutiple
- 【CodeVS1231】最优布线问题
- Canonical 准备与 Android 厂商合作推出更多 Ubuntu Phone
- Educational Codeforces Round 7 A
- 数字化运营使能系统的架构和应用部署
- java基础18io流
- matlab的一点问题
- ITOO4.1之cookie学习
- Android 6编译环境搭建 (Marshmallow)
- 【Leetcode】Binary Tree Level Order Traversal I/II AND Binary Tree Zigzag Level Order Traversal
- C++Primer第5版学习笔记(三)
- 【CODEVS1073】家族
- 科学松鼠会带你上MOOC(1):提升你的逻辑思维能力!
- Gitlab
- 326. Power of Three
- CSS手动改变DIV高宽
- 升级Oracle 10..2.0.1到Oracle 10.2.0.5
- 无处不在的Service服务
- 在CentOS 6.6 64bit上安装截图软件shutter
- css 表格