Shuffle a set of numbers without duplicates.
Example:
// Init an array with set 1, 2, and 3.
int[] nums = {1,2,3};
Solution solution = new Solution(nums);
// Shuffle the array [1,2,3] and return its result. Any permutation of [1,2,3] must equally likely to be returned.
solution.shuffle();
// Resets the array back to its original configuration [1,2,3].
solution.reset();
// Returns the random shuffling of array [1,2,3].
solution.shuffle();
这道题让我们打乱一个数组,相当于shuffle card problem。
我们可以用 Knuth-Durstenfeld Shuffle 洗牌算法 来解决这个问题
参考文章
- Knuth-Durstenfeld Shuffle
version1
class Solution {
Random rd;
int[] cards;
int[] nums;
public Solution(int[] nums) {
this.nums = nums;
this.cards = nums.clone();
this.rd = new Random();
}
/** Resets the array to its original configuration and return it. */
public int[] reset() {
this.cards = nums.clone();
return this.cards;
}
/** Returns a random shuffling of the array. */
public int[] shuffle() {
for (int i = 0; i < cards.length; i++) {
int remain = cards.length - i;
int rdIdx = rd.nextInt(remain);
int tmp = cards[i];
cards[i] = cards[i + rdIdx];
cards[i + rdIdx] = tmp;
}
return cards;
}
}
version2
public class Solution {
private int[] nums;
private Random random;
public Solution(int[] nums) {
this.nums = nums;
random = new Random();
}
/** Resets the array to its original configuration and return it. */
public int[] reset() {
return nums;
}
/** Returns a random shuffling of the array. */
public int[] shuffle() {
if(nums == null) return null;
int[] a = nums.clone();
for(int j = 1; j < a.length; j++) {
int i = random.nextInt(j + 1);
swap(a, i, j);
}
return a;
}
private void swap(int[] a, int i, int j) {
int t = a[i];
a[i] = a[j];
a[j] = t;
}
}
- 2.3 Inside-Out Algorithm
public class Solution {
private int[] nums;
public Solution(int[] nums) {
this.nums = nums;
}
/** Resets the array to its original configuration and return it. */
public int[] reset() {
return nums;
}
/** Returns a random shuffling of the array. */
public int[] shuffle() {
int[] rand = new int[nums.length];
for (int i = 0; i < nums.length; i++){
int r = (int) (Math.random() * (i+1));
rand[i] = rand[r];
rand[r] = nums[i];
}
return rand;
}
}
Inside-Out Algorithm 算法的基本思思是从前向后扫描数据,在新数组中,位置r是前i个数中任意一个位置,把位置r的数据复制到位置i中,然后把新数组中位置r的数字替换为原数组位置i的数字。。
如果知道arr的lengh的话,可以改为for循环,由于是从前往后遍历,所以可以应对arr[]数目未知的情况,或者arr[]是一个动态增加的情况。
https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle#The_%22inside-out%22_algorithm
证明:
原数组第i个数放倒前i个任意位置的概率为:
1/i * [i/(i + 1)] * [(i + 1) / (i + 1)] ...[(n - i)/n] = 1/n
我们当index = i 的时候开始放置第i个位置的数, 放置到某个位置r的概率为1/i, index 再继续往后便利的时候,我们不能再选中r的概率为 i / (i + 1), 然后可以以此类推。
原数组第i个数放倒i + 1 到 n 之间任意位置的概率是:
假设我们放到了第k个位置
此时rand(k) 等于i的概率为1/k, 并且遍历到k之后不能把k这个位置的数给替换掉.
所以概率为 i / k * [k/(k + 1)] * [(k + 1) / (k + 2)] * ... * [(n - 1)/ n] = 1/n
所以总体来说,概率是1/n