BiruLyu
8/18/2017 - 5:57 PM

## 384. Shuffle an Array(#1).java

``````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;
}
}

/**
* Your Solution object will be instantiated and called as such:
* Solution obj = new Solution(nums);
* int[] param_1 = obj.reset();
* int[] param_2 = obj.shuffle();
*/``````
``````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;
}
}

/**
* Your Solution object will be instantiated and called as such:
* Solution obj = new Solution(nums);
* int[] param_1 = obj.reset();
* int[] param_2 = obj.shuffle();
*/

/*
@Yanning For the last position, once you generate a random number in range (0,len(ans)),
you would have decided the value that is going to go in that position after shuffling.
So once the swap is done, the new element there is already in its 'random' position
(or in other words a random element of that array has been put at that position.
In the next iteration you are looking for a random index among the leftover numbers for the last but one position,
so the index has to be from a range one less.
For example, assume there are 5 numbers are in a hat,
you picked one and placed it outside ( in our case swapped it with the one in the position we are looking to fill),
Now the next time you want to pick a number from the remaining.
*/``````