您的位置:首页 > 其它

数组随机排序

2016-02-12 08:27 393 查看
以前没怎么用过,下面简单看一看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 \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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: