我正在尝试按照以下方式对整数数组进行洗牌,
并来自http://en.wikipedia.org/wiki/Fisher-Yates_shuffle,
“当 Fisher-Yates shuffle 与伪随机数生成器或 PRNG 一起使用时,会出现另一个问题:由于此类生成器输出的数字序列完全由其在序列开始时的内部状态决定,因此由此类驱动的 shuffle生成器不可能产生比生成器具有不同的可能状态更多的不同排列。......“
- 如果我用很多字节为我的 SecureRandom 生成器播种就足够了吗?
填充种子字节数组的最简单方法是什么?IE
字节[]种子=新字节[2048];// 用随机的东西填充种子字节,最简单的方法是什么?SecureRandom 安全随机 = 新的安全随机(种子);
代码:
/**
* http://en.wikipedia.org/wiki/Fisher-Yates_shuffle
*
* To shuffle an array a of n elements (indices 0..n-1):
* for i from n − 1 downto 1 do
* j ← random integer with 0 ≤ j ≤ i
* exchange a[j] and a[i]
*/
public int[] shuffle (int[] inSet ) {
int [] returnSet = Arrays.copyOf(inSet, inSet.length);
for( int i = inSet.length-1; i > 0; i-- ) {
// j ← random integer with 0 ≤ j ≤ i
int j = secureRandom.nextInt(i+1);
// swap returnSet[i] and returnSet[j]
int temp = returnSet[i];
returnSet[i] = returnSet[j];
returnSet[j] = temp;
}
return returnSet;
}