- 暴力洗牌
设原数组为 nums,用一个数组 waiting 或者是其他数据结构(如 ArrayList)保存这个数组的所有数字,然后每次随机从这个 waiting 数组中抽出一个数放在 打乱后的数组 shuffled 中。
具体实现:
Random random = new Random();
for(int i= 0;i<origins.length;i++){
int j = random.nextInt(list.size());
shuffled[i] = list.remove(j);
}
- KnuthKnuth 洗牌算法
随机交换当前坐标和其他坐标
0 可以和 [0, n -1] 中的某个坐标交换,1 可以和 [1, n-1] 中的某个坐标交换。
public int[] shuffle() {
int[] ans = nums.clone();
for (int i = 0; i < n; i++) {
swap(ans, i, i + random.nextInt(n - i));
}
return ans;
}